0

コードサンプル

- (void)drawRect:(CGRect)rect {  
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, self.frame.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height), [UIImage imageNamed:@"sample.png"].CGImage);

    CGContextRestoreGState(context);    
}

================

画像内の特定の四角形をコンテキストにコピーしたいので、画像全体が描画されるのではなく、画像の一部だけが描画されます。誰かがこれに対する解決策を持っていますか? Googleでもドキュメントでも何も見つかりません。

次のような代替手段があることは知っています: 1. クリッピングを使用して UIView を作成し、その中に UIImageView を配置します。2. UIScrollView 内に UIImageView を作成し、コンテンツ オフセットを使用します。

しかし、私はそれらが不自由だと思います...

4

3 に答える 3

7

CGImageCreateWithImageInRect は正常に動作するはずです。それが私のやり方です。次に例を示します。

CGImageRef ref = CGImageCreateWithImageInRect(some_UIImage.CGImage, CGRectMake(x, y, height, width));
UIImage *img = [UIImage imageWithCGImage:ref];

この例では、UIImage のインスタンスである another_UIImage の CGImage プロパティから CGImageRef を取得し、トリミングして、UIImage の imageWithCGImage コンストラクター メソッドを使用して UIImage に戻します。幸運を!

ジェームズ

于 2010-04-19T23:55:00.097 に答える
1

これはうまくいきました:

UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);

CGRect drawRect = CGRectMake(rect.origin.x * -1,
                             rect.origin.y * -1,
                             imageToCrop.size.width,
                             imageToCrop.size.height);

CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
于 2010-04-19T21:09:31.167 に答える
1

CGImageCreateWithImageInRect を試すことができます

于 2010-04-19T20:58:07.107 に答える