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



目录
相关文章
|
iOS开发
iOS动画开发之三——UIView的转场切换
iOS动画开发之三——UIView的转场切换
401 0
|
iOS开发
iOS 利用UIScrollView实现图片放大预览,并支持缩小
iOS 利用UIScrollView实现图片放大预览,并支持缩小
554 0
iOS 利用UIScrollView实现图片放大预览,并支持缩小
|
前端开发 Android开发 数据格式
|
编解码 iOS开发
iOS中图片(UIImage)拉伸技巧
iOS中图片(UIImage)拉伸技巧
379 0
iOS中图片(UIImage)拉伸技巧
|
iOS开发
ios tableView那些事 (十一) 让 tableview 不可滚动或屏蔽掉
<p class="p1" style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px"> <span style="font-size:18px">-(<span class="s1">
2534 0
|
编解码 前端开发 Android开发
照相机预览、拍照以及适配问题的完美解决
         前段时间在做face++相关的功能,对于照相机也是进行了一番研究,小有收获,很感谢有一些大神已经写了相应的博客,让我在他们的项目上进行完善和优化,修复了一些bug,并对机型适配做了一些处理,目前已经保证了团队里面十多部安卓手机的完美适配,具体项目资源可以在http://download.csdn.net/detail/shan286/9799622这个网址上下载。
1432 0

热门文章

最新文章