将UIView捕获为UIImage

时间:2011-08-24 14:57:38

标签: objective-c ios uiview uiimageview uiimage

我一直在使用此方法将UIView转换为UIImage。即视图的屏幕快照 -

@interface UIView(Extended) 

- (UIImage *) imageByRenderingView;

@end


@implementation UIView(Extended)


- (UIImage *)imageByRenderingView
{   
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

@end

要使用它,我这样做 -

UIImage *currImage = [self.view imageByRenderingView];

这给出了整个UIView的图像表示。现在我想要2个图像,一个是UIView的上半部分,另一个是下半部分。我该怎么做?

1 个答案:

答案 0 :(得分:11)

您可以使用以下代码将UIImage拆分为两个:

CGImageRef topOfImageCG =
         CGImageCreateWithImageInRect(currImage.CGImage,
                                      CGRectMake(0,
                                                 0,
                                                 currImage.size.width,
                                                 currImage.size.height / 2.0));

UIImage *topOfImage = [UIImage imageWithCGImage:topOfImageCG];

CGImageRelease(topOfImageCG);