zoukankan      html  css  js  c++  java
  • 图片的裁剪

    Main.storyboard

    ViewController.m

    //

    //  ViewController.m

    //  6A01.图片的裁剪(位图上下文)

    //

    //  Created by huan on 16/1/29.

    //  Copyright © 2016 huanxi. All rights reserved.

    //

     

    #import "ViewController.h"

     

    @interface ViewController ()

    @property (weak, nonatomic) IBOutlet UIImageView *imgView;

     

    @end

     

    @implementation ViewController

     

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

    }

     

    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

        //需求:从位图上下文,裁剪图片[裁剪成圆形,也添加圆形的边框],生成一张图片

        //获取要裁剪的图片

        UIImage *img = [UIImage imageNamed:@"papa"];

        //1.开启位图上下文

        UIGraphicsBeginImageContextWithOptions(img.size, NO, 0.0);

        CGRect imgRect = CGRectMake(0, 0, img.size.width, img.size.height);

        //1.1 获取当前位图上下文

    #warning 在自定义的viewdrawRect方法里,调用UIGraphicsGetCurrentContext获取的上下文,是图层上下文(Layeer Graphics Context

        CGContextRef bitmapContext = UIGraphicsGetCurrentContext();

        //2.往位图上下文剪裁图片

        //2.1 指定一个圆形的路径,把圆形之外的剪切掉

        CGContextAddEllipseInRect(bitmapContext, imgRect);

        CGContextClip(bitmapContext);

        

        //2.2 添加图片

        [img drawInRect:imgRect];

        

        //2.3 添加边框

        //设置边框的宽度

        CGContextSetLineWidth(bitmapContext, 3);

        //设置边框的颜色

        [[UIColor blueColor] set];

        CGContextAddEllipseInRect(bitmapContext, imgRect);

        CGContextStrokePath(bitmapContext);

        //3. 获取当前位图上下文的图片

        UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();

        //4. 结束位图编辑

        UIGraphicsEndImageContext();

        //把图片显示在控制器的view

        self.imgView.image = newImg;

        

        //保存图片,先把图片转成NSData,然后调用其的write

        NSData *imgData = UIImagePNGRepresentation(newImg);

        [imgData writeToFile:@"/Users/huan/Desktop/new.png" atomically:YES];

     

    }

     

    - (void)didReceiveMemoryWarning {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    @end

  • 相关阅读:
    设计模式之工厂模式-抽象工厂(02)
    1036 跟奥巴马一起编程 (15 分)
    1034 有理数四则运算 (20 分)
    1033 旧键盘打字 (20 分)
    1031 查验身份证 (15 分)
    大学排名定向爬虫
    1030 完美数列 (25 分)二分
    1029 旧键盘 (20 分)
    1028 人口普查 (20 分)
    1026 程序运行时间 (15 分)四舍五入
  • 原文地址:https://www.cnblogs.com/Lu2015-10-03/p/5177773.html
Copyright © 2011-2022 走看看