来自UIView地区的UIImage

alm*_*now 8 iphone uiview uiimage ios

我想剪辑的区域UIView,成为UIImage以备后用.

我从一些片段中找出了这段代码:

 CGRect _frameIWant = CGRectMake(100, 100, 100, 100);

 UIGraphicsBeginImageContext(view.frame.size);
 [view.layer renderInContext:UIGraphicsGetCurrentContext()];

 //STEP A: GET AN IMAGE FOR THE FULL FRAME
 UIImage *_fullFrame = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 //STEP B: CLIP THE IMAGE
 CGImageRef _regionImage = CGImageCreateWithImageInRect([_fullFrame CGImage], _frameIWant);
 UIImage *_finalImage = [UIImage imageWithCGImage:_regionImage];
 CGImageRelease(_regionImage);
Run Code Online (Sandbox Code Playgroud)

'view'是UIView我剪裁的,_finalImageUIImage我想要的.

代码工作没有问题,但有点慢.我相信通过在步骤A中直接获取部分屏幕可以获得一些性能.

我正在寻找类似的东西renderInContext: withRect:或者UIGraphicsGetImageFromCurrentImageContextWithRect()呵呵.

还没有找到任何东西:(如果你知道一些替代方案,请帮助我.

Fel*_*lix 6

此方法使用较少的内存和CPU时间剪切视图的区域:

-(UIImage*)clippedImageForRect:(CGRect)clipRect inView:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(clipRect.size, YES, 1.f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, -clipRect.origin.x, -clipRect.origin.y);
    [view.layer renderInContext:ctx];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
Run Code Online (Sandbox Code Playgroud)