【代碼筆記】iOS-對UIView進行截圖

一,效果圖。spa

二,工程圖。code

三,代碼。blog

RootViewController.m圖片

複製代碼
#import "RootViewController.h"


@interface RootViewController ()

@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //UIView
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];
    view.backgroundColor=[UIColor redColor];
    [self.view addSubview:view];
    
    //在UIImageView中顯示截取的圖片
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 200, 200, 100)];
    imageView.image=[self screenShotView:view];
    [self.view addSubview:imageView];
}
#pragma -mark -functions
// 對指定視圖進行截圖
- (UIImage *)screenShotView:(UIView *)view
{
    UIImage *imageRet = nil;
    
    if (view)
    {
        if(UIGraphicsBeginImageContextWithOptions)
        {
            UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
        }
        else
        {
            UIGraphicsBeginImageContext(view.frame.size);
        }
        
        //獲取圖像
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        imageRet = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }else{
    }
    
    return imageRet;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
複製代碼
相關文章
相關標籤/搜索