UIView的無損截圖


UIView的無損截圖

 

 

說明

1. 爛大街的代碼

2. 寫成category后,方便直接從drawRect中獲取繪制出來的圖片

3. 可以直接繪制圖片供按鈕設置背景圖片用

4. 無損截圖(包括alpha通道值也被無損保存)

 

源碼

//
//  UIView+ScreensShot.h
//  ColorfulView
//
//  Created by YouXianMing on 15/7/17.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (ScreensShot)

/**
 *  無損截圖 
 *
 *  This function may be called from any thread of your app.
 *
 *  @return 返回生成的圖片
 */
- (UIImage *)screenShot;

@end
//
//  UIView+ScreensShot.m
//  ColorfulView
//
//  Created by YouXianMing on 15/7/17.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "UIView+ScreensShot.h"
#import <objc/runtime.h>

@implementation UIView (ScreensShot)

- (UIImage *)screenShot {
    
    if (self && self.frame.size.height && self.frame.size.width) {
        
        UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return image;
        
    } else {
    
        return nil;
    }

}

@end
//
//  ViewController.m
//  ColorfulView
//
//  Created by YouXianMing on 15/7/10.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "UIView+ScreensShot.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.view.backgroundColor = [UIColor blackColor];
    
    UIView *cyanView         = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
    cyanView.backgroundColor = [UIColor cyanColor];
    cyanView.alpha           = 0.5f;
    [self.view addSubview:cyanView];

    UIImageView *imageView   = [[UIImageView alloc] initWithImage:[cyanView screenShot]];
    imageView.frame          = CGRectMake(80, 80, 100, 100);
    [self.view addSubview:imageView];
}



@end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM