4

我有一个绘图应用程序,我想创建 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];

}
4

2 回答 2

2

您是否使用“时间分析器”工具(“产品”菜单 ->“配置文件”)来检查您在代码中花费最多时间的位置?(当然,将它与您的设备一起使用,而不是模拟器,以获得真实的配置文件)。我猜它不在您在问题中引用的图像捕获部分中,而是在您的重新缩放imageWithImage:scaledToSize:方法中。

与其在上下文中以整个大小渲染图像,然后将图像重新缩放到最终大小,不如通过对上下文应用一些仿射变换直接以预期大小在上下文中渲染层

所以只需在你的 line 之后使用CGContextConcatCTM(someScalingAffineTransform);on ,应用缩放仿射变换,使图层以不同的比例/大小呈现。UIGraphicsGetCurrentContext()UIGraphicsBeginImageContext(size);

这样,它将直接渲染为预期大小,这将更快,而不是以 100% 渲染,然后让您以耗时的方式重新调整它

于 2013-02-09T11:48:27.027 回答
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;

    }
于 2013-02-12T18:58:01.373 回答