0

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

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

这工作正常。如果UIView500 像素高,并且我想生成两个图像(一个上半部分和一个下半部分),我该怎么做呢?

任何帮助将不胜感激。

4

1 回答 1

1

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

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);
于 2012-09-29T03:08:03.463 回答