捕获UIView的屏幕截图-性能缓慢



我有一个绘图应用程序,我想创建Canvas UIView的快照(屏幕内外),然后缩小它。我在iPad3上做这件事的代码永远都是该死的。模拟器没有延迟。画布为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];
}

您是否使用"时间档案器"工具("产品"菜单->"档案")来检查您在代码中花费的时间最多?(当然,将它与您的设备一起使用,而不是与模拟器一起使用,以便进行真实的评测)。我想这不是你在问题中引用的图像捕获部分,而是你的重新缩放方法imageWithImage:scaledToSize:方法。

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

因此,只需在UIGraphicsBeginImageContext(size);行之后的UIGraphicsGetCurrentContext()上使用CGContextConcatCTM(someScalingAffineTransform);,即可应用缩放仿射变换,使层以不同的比例/大小进行渲染。

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

谢谢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;
    }

最新更新