zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    设计模式之策略模式
    设计模式之简单工厂模式
    UML 之关系
    C# delegate (001)
    转: 编写高质量代码改善C#程序的157个建议
    通过配置数据库邮件实现发送邮件
    存储过程学习(004)--象写程序一样的写存储过程及调试
    存储过程学习(003)--象写程序一样的写存储过程及调试
    存储过程学习(002)--循环插入数据
    jQ新的事件绑定方法on()
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4655835.html
Copyright © 2011-2022 走看看