首页 > 其他 > 详细

图片的裁剪

时间:2016-02-02 16:39:19      阅读:287      评论:0      收藏:0      [点我收藏+]

技术分享

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

技术分享

图片的裁剪

原文:http://www.cnblogs.com/Lu2015-10-03/p/5177773.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!