iPhone:如何将视图保存为图像??? (ex.save你画的是什么)

时间:2011-05-21 02:41:03

标签: iphone objective-c ios uiview uiimage

我发现一些样本教你如何在iphone上绘图

但它没有说明如何将视图保存为图像?

有没有人有想法???

或者任何样本都会有所帮助:)

实际上,我正在尝试将用户的签名保存为图像并将其上传到服务器。

谢谢

韦伯

3 个答案:

答案 0 :(得分:33)

UIView *view = // your view    
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这将为您提供可以使用的图像 -

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[imageData writeToFile:path atomically:YES];

其中path是您要保存到的位置。

答案 1 :(得分:4)

这是一种将任何UIView渲染为图像的快速方法。它考虑了设备运行的iOS版本,并利用相关方法获取UIView的图像表示。

更具体地说,现在有更好的方法(即drawViewHierarchyInRect:afterScreenUpdates :)用于在iOS 7或更高版本上运行的设备上截取UIView,这是从我读过的,被认为是更多与“renderInContext”方法相比,性能更佳。

此处有更多信息:https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW217

使用示例:

#import <QuartzCore/QuartzCore.h> // don't forget to import this framework in file header.

UIImage* screenshotImage = [self imageFromView:self.view]; //or any view that you want to render as an image.

<强> CODE:

#define IS_OS_7_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

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

    CGFloat scale = [UIScreen mainScreen].scale;
    UIImage *image;

    if (IS_OS_7_OR_LATER) {
        //Optimized/fast method for rendering a UIView as image on iOS 7 and later versions.
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, scale);
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        //For devices running on earlier iOS versions.
        UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES, scale);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return image;
}

答案 2 :(得分:1)

在MonoTouch / C#中作为扩展方法:

public static UIImage ToImage(this UIView view) {
    try {
        UIGraphics.BeginImageContext(view.ViewForBaselineLayout.Bounds.Size);
        view.Layer.RenderInContext(UIGraphics.GetCurrentContext());
        return UIGraphics.GetImageFromCurrentImageContext();
    } finally {
        UIGraphics.EndImageContext();
    }
}