2

UIImage を使用して NSImage の drawInRect:fromRect:operation:fraction の動作をエミュレートする必要があり、誰かが既にこれを行っており、コードを共有する意思があるかどうか、または (より良い) 最善のアプローチは何か疑問に思っています。

CGImageCreateWithImageInRect (最後のコードを参照) を使用してこれを実行しようとしましたが、期待した結果が得られません。コードは実際にMacでこれをテストしていることに注意してください(現時点ではiPhoneですべてを実行することはできません)ので、NSImageからCGImageを取得する際に問題が発生する可能性があります

- (void)drawInRect:(CGRect)rect fromRect:(CGRect)fromRect alpha:(float)alpha {
      CGContextRef context;
       CGImageRef originalImageRef;
       CGImageRef subimageRef;

#if ERMac
       context=[[NSGraphicsContext currentContext] graphicsPort];

       CGImageSourceRef source;

       source = CGImageSourceCreateWithData((CFDataRef)[self TIFFRepresentation], NULL);
       originalImageRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
       CFRelease(source);
#else
       context=UIGraphicsGetCurrentContext();
       originalImageRef=CGImageRetain([self CGImage]);
#endif

       subimageRef = CGImageCreateWithImageInRect (originalImageRef, fromRect);


       CGContextDrawImage(context, rect, subimageRef);


       if (subimageRef)
           CGImageRelease(subimageRef);
       if (originalImageRef)
           CGImageRelease(originalImageRef);
 }
4

3 に答える 3

2

This is how I do it...

- (void)drawInRect:(CGRect)drawRect fromRect:(CGRect)fromRect operation:(CGBlendMode)blendMode fraction:(CGFloat)alpha
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextClipToRect(context, drawRect);

    CGFloat xScale = (drawRect.size.width/fromRect.size.width);
    CGFloat yScale = (drawRect.size.height/fromRect.size.height);

    CGFloat scale = 1;
    if([self respondsToSelector:@selector(scale)])
    {
        scale = self.scale;
    }

    CGFloat actualWidth = (xScale * self.size.width)*scale;
    CGFloat actualHeight = (yScale * self.size.height)*scale;
    CGFloat xInset = fromRect.origin.x * xScale;
    CGFloat yInset = fromRect.origin.y * yScale;

    // Take care of Y-axis inversion problem by translating the context on the y axis
    CGContextTranslateCTM(context, 0, drawRect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(-xInset + drawRect.origin.x, -yInset + drawRect.origin.y, actualWidth, actualHeight), self.CGImage);

    CGContextRestoreGState(context);
}
于 2013-09-17T01:58:19.510 に答える
0

UIImage には drawInRect:blendMode:alpha: があります。UIImage のサブ長方形を抽出するための簡単な方法は、抽出したい長方形のサイズであるターゲット コンテキストに描画し、描画されたイメージの原点を左上に調整して、右側の部分がターゲットに収まるようにすることです。環境。

CGImage もこれを行う良い方法ですが、iPhone で座標系が反転するという問題が発生する場合があります。簡単な解決策は、CGImage を UIImage にラップして描画することです。これは、UIImage がどの方向に描画するかを知っているためです。

于 2011-02-09T22:01:23.287 に答える