• 图片的裁剪


    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

  • 相关阅读:
    提高SQL查询效率
    数据库主键设计之思考
    Hlg 1030 排序
    Hdu 1556 成段更新.cpp
    Hdu 4280 最大流<模板>.cpp
    POJ 3216 最短路径匹配+floyd
    Hdu 4268 multiset函数的应用
    ZOJ 3602 树的同构
    Hdu 4284 状态DP 能否走完所选城市.cpp
    Hlg 1481 二分图匹配+二分.cpp
  • 原文地址:https://www.cnblogs.com/Lu2015-10-03/p/5177773.html
Copyright © 2020-2023  润新知