将UIView捕获为UIImage(Capture UIView as UIImage)

IPhone IT屋
百度翻译此文   有道翻译此文
问 题

I have been using this method to convert a UIView into UIImage. i.e. screen snapshot of a view -

@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

To use it, I do this -

UIImage *currImage = [self.view imageByRenderingView];

This gives the image representation of the entire UIView. Now I want 2 images, one is of the top half of the UIView and the other is the bottom half. How do I do that?

解决方案

You can split your UIImage in two by using this code:

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

UIImage *topOfImage = [UIImage imageWithCGImage:topOfImageCG];

CGImageRelease(topOfImageCG);

本文地址:IT屋 » Capture UIView as UIImage

问 题

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



  @interface UIView(扩展)

- (UIImage *) imageByRenderingView;

@end


@implementation UIView(扩展)


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

@end


要使用它,我会这样做这个 -



UIImage * currImage = [self.view imageByRenderingView];



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


解决方案

你可以拆分你的 UIImage 两个使用此代码:



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

UIImage * topOfImage = [UIImage imageWithCGImage:topOfImageCG];

CGImageRelease(topOfImageCG);

本文地址:IT屋 » 将UIView捕获为UIImage

官方微信
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起