2010-02-21 75 views
2

我真的需要模拟NSImage的drawInRect行为:fromRect:operation:使用UIImage的分数,我想知道什么是最好的方法或(更好),如果有人已经做了这并愿意分享代码。我试过这样做使用CGImageCreateWithImageInRect(见代码在最后),但我没有得到预期的结果。请注意,代码实际上是在Mac上测试这个(我不能运行在iPhone截至目前整个事情),所以我可能有一些问题与NSImage中仿真NSImage drawInRect:fromRect:operation:使用UIImage的分数

- (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); 
} 

回答

0

的UIImage有drawInRect获取CGImage:的BlendMode:阿尔法:.提取UIImage的子矩形的一个简单的技巧是绘制一个目标上下文,该上下文是要提取的矩形的大小,将绘制图像的原点向上和向左调整,以便右侧部分落入目标中上下文。

CGImage也是一个很好的方法来做到这一点,但是你可能会遇到在iPhone上翻转坐标系统的问题。一个简单的解决方案是将CGImage封装到UIImage中并绘制它,因为UIImage知道要绘制哪个方向。

2

这是我要做的事......

- (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); 
}