iPhone:你怎么画一幅图像

时间:2010-04-19 20:43:36

标签: iphone xcode image drawrect

代码示例

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

=====

我想将图像中的某个矩形复制到上下文中,因此不是绘制整个图像而只是图像的一部分。有人有解决方案吗?我在谷歌和文档上找不到任何东西。

我知道有其他选择: 1.创建一个带有剪切的UIView,然后将UIImageView放在其中。 2.在UIScrollView中创建UIImageView并使用内容偏移。

但我认为那些是蹩脚的......

3 个答案:

答案 0 :(得分:7)

CGImageCreateWithImageInRect应该可以正常工作。我就是这样做的。这是一个例子:

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

此示例从another_UIImage的CGImage属性获取CGImageRef,这是UIImage的一个实例,然后裁剪它,并使用UIImage的imageWithCGImage构造方法将其转换回UIImage。祝你好运!

詹姆斯

答案 1 :(得分:1)

您可以尝试CGImageCreateWithImageInRect

答案 2 :(得分: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();