来自UIView区域的UIImage
问题描述:
我试图将UIView
的区域剪切为UIImage
以备后用。来自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);
“视图”是我削波和_finalImage
是UIImage
我想要的UIView
。
该代码工作没有问题,但是有点慢。我相信通过直接在步骤A中取得部分屏幕可以获得一些性能。
我正在寻找类似renderInContext: withRect:
或UIGraphicsGetImageFromCurrentImageContextWithRect()
的东西呵呵。
仍然没有发现任何东西:(,请帮助我,如果你知道一些替代的
答
此方法剪辑使用较少的存储器和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;
}
答
你可以尝试先栅格化的UIView:
view.layer.shouldRasterize = YES;
我一直在使用这个有限的成功,但是说我正在做和你一样的东西(加上上面的一行),并且它工作正常。在什么情况下你做这件事?这可能是你的性能问题。
编辑:你也可以尝试使用视图的界限而不是视图的框架并不总是相同的。
+0
我认为这是'主要'的背景。我在主线上创建了一个新的上下文。 :S – almosnow 2010-11-16 22:15:12
答
的@夫特版本phix23溶液。 加入刻度
func clippedImageForRect(clipRect: CGRect, inView view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(clipRect.size, true, UIScreen.mainScreen().scale);
let ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, -clipRect.origin.x, -clipRect.origin.y);
view.layer.renderInContext(ctx!)
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img
}
你能重新格式化吗?难以阅读 – Rudiger 2010-10-12 20:49:34