LoginSignup
7
7

More than 5 years have passed since last update.

Viewのキャプチャを取得する方法

Posted at
+ (UIImage *)imageFromView:(UIView *)view{

    CGRect rect = view.bounds;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return capturedImage;
}

UIImageのカテゴリとしました。

UIImage+ViewConvert.h
#import <UIKit/UIKit.h>

@interface UIImage (ViewConvert)
+ (UIImage *)imageFromView:(UIView *)view;
@end
UIImage+ViewConvert.m
#import "UIImage+ViewConvert.h"

@implementation UIImage (ViewConvert)
+ (UIImage *)imageFromView:(UIView *)view{

    CGRect rect = view.bounds;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return capturedImage;
}
@end

これを使って簡単なサンプルを作成。
起動すると写真がはいった画面を表示します。
1.png

1.commentボタンを押すと、写真にラベルが表示されます。
2.png

2.tweetボタンを押すと、ラベル表示が入った写真をTwitterに投稿するためのメッセージ入力画面が表示されます。
3.png

サンプルはこちら

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7