来自UIView的图片

时间:2010-08-16 16:53:13

标签: objective-c uiview

是否有可能用UIView创建图像?

谢谢, 安德烈亚斯

2 个答案:

答案 0 :(得分:47)

将框架添加到项目后

#import "QuartzCore/QuartzCore.h"。然后做:

UIGraphicsBeginImageContext(yourView.frame.size);
[[yourView layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// The result is *screenshot

答案 1 :(得分:1)

我已经用答案进一步改进了它。不幸的是,原始代码只生成了一个镜像图像。

所以这是工作代码:

- (UIImage *) imageFromView:(UIView *)view {

    UIGraphicsBeginImageContext(view.frame.size);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, 0, view.size.height);
    // passing negative values to flip the image
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    [[appDelegate.scatterPlotView layer] renderInContext:currentContext];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshot;
}