我有各种各样的绘图应用程序,我想创建一个Canvas UIView的快照(打开和关闭屏幕),然后缩小它。我做的那些代码在iPad上永远都是血腥的3.模拟器没有延迟。画布是2048x2048。
我应该采取另一种方式吗?或者我在代码中遗漏了什么?
谢谢!
-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
// Size of our View
CGSize size = editorContentView.bounds.size;
//First Grab our Screen Shot at Full Resolution
UIGraphicsBeginImageContext(size);
[editorContentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Calculate the scal ratio of the image with the width supplied.
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = width / size.width;
} else {
ratio = width / size.height;
}
//Setup our rect to draw the Screen shot into
CGSize newSize = CGSizeMake(ratio * size.width, ratio * size.height);
//Send back our screen shot
return [self imageWithImage:screenShot scaledToSize:newSize];
}
答案 0 :(得分:2)
您是否使用“Time Profiler”工具(“产品”菜单 - >“个人资料”)检查代码中您花费大部分时间的位置? (当然,使用它与您的设备,而不是模拟器,以实现真实的分析)。我猜它不在您在问题中引用的图像捕获部分,而是在您的重新缩放方法imageWithImage:scaledToSize:
方法中。
不是在上下文中以整个尺寸渲染图像,而是将图像重新缩放到最终尺寸,通过对上下文应用一些仿射变换,您应该直接以预期大小渲染上下文中的图层< /强>
只需在行CGContextConcatCTM(someScalingAffineTransform);
后面的UIGraphicsGetCurrentContext()
上使用 UIGraphicsBeginImageContext(size);
,即可应用缩放仿射变换,使图层呈现不同规模/尺寸。
通过这种方式,它将直接呈现为预期的大小,速度会快得多,而不是以100%渲染,然后让您以耗时的方式重新缩放它
答案 1 :(得分:0)
谢谢AliSoftware,以下是我最终使用的代码:
-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
if (IoUIDebug & IoUIDebugSelectorNames) {
NSLog(@"%@ - %@", INTERFACENAME, NSStringFromSelector(_cmd) );
}
// Size of our View
CGSize size = editorContentView.bounds.size;
//Calculate the scal ratio of the image with the width supplied.
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = width / size.width;
} else {
ratio = width / size.height;
}
CGSize newSize = CGSizeMake(ratio * size.width, ratio * size.height);
//Create GraphicsContext with our new size
UIGraphicsBeginImageContext(newSize);
//Create Transform to scale down the Context
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformScale(transform, ratio, ratio);
//Apply the Transform to the Context
CGContextConcatCTM(UIGraphicsGetCurrentContext(),transform);
//Render our Image into the the Scaled Graphic Context
[editorContentView.layer renderInContext:UIGraphicsGetCurrentContext()];
//Save a copy of the Image of the Graphic Context
UIImage* screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenShot;
}