繁体   English   中英

iOS-仅将UIView的一部分保存到PNG

[英]iOS - Saving only a part of a UIView to PNG

我正在使用以下代码将UIView的内容转换为PNG图像:

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这很好。 如果UIView高为500像素,并且我想生成两张图像(上半部之一,下半部之一),该如何处理?

任何帮助将不胜感激。

有几种方法可以做到这一点。 一种方法是将其绘制成一个大图像,然后制作两个子图像:

static UIImage *halfOfImage(UIImage *fullImage, CGFloat yOffset) {
    // Pass yOffset == 0 for the top half.
    // Pass yOffset == 0.5 for the bottom half.

    CGImageRef cgImage = fullImage.CGImage;
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    CGRect rect = CGRectMake(0, height * yOffset, width, height * 0.5f);

    CGImageRef cgSubImage = CGImageCreateWithImageInRect(cgImage, rect);
    UIImage *subImage = [UIImage imageWithCGImage:cgSubImage scale:fullImage.scale
        orientation:fullImage.imageOrientation];
    CGImageRelease(cgSubImage);
    return subImage;
}

...
    UIGraphicsBeginImageContext(myView.bounds.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImage *topHalfImage = halfOfImage(viewImage, 0);
    UIImage *bottomHalfImage = halfOfImage(viewImage, 0.5f);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM