gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:23:42 25 4
gpt4 key购买 nike

我使用以下代码将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com