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

标签 ios uiview 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);

关于iOS - 仅将 UIView 的一部分保存为 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649548/

相关文章:

objective-c - 实例和方法的命名约定

ios - 如何将 HSB 彩色滤镜应用到 UIImage

ios - 如何控制 UIViewController 的 View 框架

cocoa-touch - 动画内在内容大小的变化

CSS - 使用过滤器为黑白 PNG 图像添加颜色

python-3.x - 如何将绘图(由 shap_values 生成)保存到 png?

python - 是否可以使用 Python 为 iOS 和 Android 编写跨平台应用程序?

Android和iOS应用共享类图

objective-c - 对象-C : UIView from Nib being released between willAppear and didAppear

c++ - PNG++ 读取像素颜色值