Quartz2D_Day4 基本应用


2020年04月14日更新

使用UIBezierPath addClip方法添加裁剪区域的方式

@interface ViewController ()
@property (nonatomic, strong, readwrite) UIImageView      *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 加载图片
    UIImage *image = [UIImage imageNamed:@"测试"];
    // 2. 创建bitMap位图上下文
    // opaque 不透明度
    UIGraphicsBeginImageContextWithOptions(image.size, 0, 0);
    // 3. 设置一个圆形的裁剪区域
    // 3.1 绘制一个圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    // 3.2 把圆形路径设置成裁剪区域
    [path addClip];
    // 4.将图片添加到位图上下文中(超过裁剪区域i以外的内容都给裁剪掉)
    [image drawAtPoint:CGPointZero];
    // 5.把上下文当中绘制的所有内容,生成一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 6.关闭位图上下文
    UIGraphicsEndImageContext();
    
    [self.view addSubview:self.imageView];
    self.imageView.image = newImage;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    }
    return _imageView;
}

@end

带有边框的图片裁剪

效果图
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong, readwrite) UIImageView      *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 带有边框的圆形图片裁剪
    
    // 0. 加载图片
    UIImage *image = [UIImage imageNamed:@"测试"];
    // 1. 确定边框宽度
    CGFloat borderWidth = 5;
    // 2. 开启一个上下文
    CGSize size = CGSizeMake(image.size.width + 2*borderWidth, image.size.height + 2*borderWidth);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    // 3. 绘制底图大圆
    UIBezierPath *borderCircle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [[UIColor redColor] set];
    [borderCircle fill];
    // 4. 绘制一个小圆,并设置为裁剪区域
    UIBezierPath *imageCircle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height)];
    [imageCircle addClip];
    // 5. 把图片绘制到上下文当中
    [image drawAtPoint:CGPointMake(borderWidth, borderWidth)];
    // 6. 从上下文中生成图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 7. 关闭上下文
    UIGraphicsEndImageContext();
    
    [self.view addSubview:self.imageView];
    self.imageView.image = newImage;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    }
    return _imageView;
}

@end

可以封装成一个UIImage的分类,使用起来更方便

@interface UIImage (Circleimage)
/// 生成一张带有边框的圆形图片
/// @param imgName 图片名称
/// @param borderWidth 边框宽度
/// @param borderColor 边框颜色
+ (UIImage *)circleImageWithImageName:(NSString *)imgName borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;


/// 生成一张带有边框的圆形图片
/// @param borderWidth 边框宽度
/// @param borderColor 边框颜色
- (UIImage *)circleImageWithBorderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;
@end


#import "UIImage+Circleimage.h"
@implementation UIImage (Circleimage)

+ (UIImage *)circleImageWithImageName:(NSString *)imgName borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
    UIImage *image = [UIImage imageNamed:imgName];
    return [image circleImageWithBorderWidth:borderWidth borderColor:borderColor];
}

- (UIImage *)circleImageWithBorderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
    // 0. 加载图片
    UIImage *image = self;
    // 2. 开启一个上下文
    CGSize size = CGSizeMake(image.size.width + 2*borderWidth, image.size.height + 2*borderWidth);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    // 3. 绘制底图大圆
    UIBezierPath *borderCircle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [borderColor set];
    [borderCircle fill];
    // 4. 绘制一个小圆,并设置为裁剪区域
    UIBezierPath *imageCircle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height)];
    [imageCircle addClip];
    // 5. 把图片绘制到上下文当中
    [image drawAtPoint:CGPointMake(borderWidth, borderWidth)];
    // 6. 从上下文中生成图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 7. 关闭上下文
    UIGraphicsEndImageContext();
    return newImage;
}

@end


截屏

#import "ViewController.h"
#import "UIImage+Circleimage.h"

@interface ViewController ()
@property (nonatomic, strong, readwrite) UIImageView      *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 带有边框的圆形图片裁剪
    UIImage *image = [UIImage imageNamed:@"测试"];
    [self.view addSubview:self.imageView];
    self.imageView.image = [image circleImageWithBorderWidth:10 borderColor:[UIColor blueColor]];;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    }
    return _imageView;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 点击屏幕截屏,并且把图片保存在电脑桌面(所以必须使用模拟器运行才能保存成功)
    
    // 1.0 开启一个位图上下文(跟当前控制器view一样的大小尺寸)
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
    // 2.0 将控制器的view绘制到上下文当中
    // 想要把UIView绘制到上下文当中,必须使用渲染的方式
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:ctx];
    
    // 3.0 从上下文中生成一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.0 关闭上下文
    UIGraphicsEndImageContext();
    
    // 5.0 将生成的图片写入到桌面(文件方式进行传输:二进制流NSData)
    // 将图片转成二进制流NSData
    NSData *data = UIImageJPEGRepresentation(newImage, 1);
    [data writeToFile:@"/Users/liven/Desktop/newImage.jpg" atomically:YES];
}


@end

图片裁剪

moveTouch.gif
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong, readwrite) UIImageView      *imageView;
@property (nonatomic, assign, readwrite) CGPoint           startPoint;
@property (nonatomic, weak  , readwrite) UIView           *corverView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.imageView];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [self.imageView addGestureRecognizer:pan];
    
}

- (void)panAction:(UIPanGestureRecognizer *)pan {
    CGPoint currentPoint = [pan locationInView:self.imageView];
    if (pan.state == UIGestureRecognizerStateBegan) {
        self.startPoint = currentPoint;
    }
    else if (pan.state == UIGestureRecognizerStateChanged) {
        CGFloat x = self.startPoint.x;
        CGFloat y = self.startPoint.y;
        CGFloat w = currentPoint.x - self.startPoint.x;
        CGFloat h = currentPoint.y - self.startPoint.y;
        CGRect rect = CGRectMake(x, y, w, h);
        self.corverView.frame = rect;
    }
    else if (pan.state == UIGestureRecognizerStateEnded) {
        CGRect rect = self.corverView.frame;
        // 移除蒙版
        [self.corverView removeFromSuperview];
        
        // 开启位图上下文
        UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
        // 绘制一个跟蒙层corverView相同大小的裁剪去
        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:rect];
        [bezierPath addClip];
        // 将imageView渲染到上下文当中
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        [self.imageView.layer renderInContext:ctx];
        // 通过上下文生成一张图片
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭上下文
        UIGraphicsEndImageContext();
        
        // 将新生成的图片替换之前的图片
        self.imageView.image = newImage;
    }
    
}


- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"测试"]];
        _imageView.frame = self.view.bounds;
        _imageView.userInteractionEnabled = YES;
    }
    return _imageView;
}

- (UIView *)corverView {
    if (!_corverView) {
        UIView *coverView = [[UIView alloc]init];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.7;
        _corverView = coverView;
        [self.view addSubview:coverView];
    }
    return _corverView;
}


@end

图片擦拭

moveTouch.gif
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong, readwrite) UIImageView      *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.imageView];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [self.imageView addGestureRecognizer:pan];
    
}

- (void)panAction:(UIPanGestureRecognizer *)pan {
    // 获取当前手指的点
    CGPoint currentPoint = [pan locationInView:self.imageView];
    // 设置擦拭区域
    CGFloat rectWH = 20;
    CGFloat x = currentPoint.x - rectWH*0.5;
    CGFloat y = currentPoint.y - rectWH*0.5;
    CGRect rect = CGRectMake(x, y, rectWH, rectWH);
    
    // 开启一个透明的位图上下文
    UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0);
    
    // 将imageViewr渲染到上下文中
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.imageView.layer renderInContext:ctx];
    
    // 擦除上下文当中指定的区域
    CGContextClearRect(ctx, rect);
    
    // 从上下文生成一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    self.imageView.image = newImage;
}


- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"测试"]];
        _imageView.frame = self.view.bounds;
        _imageView.userInteractionEnabled = YES;
    }
    return _imageView;
}


@end

雪花划落

two.gif
#import "SnowView.h"

@interface SnowView()
@property (nonatomic,assign) float imagaeY;

@end

@implementation SnowView

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //CADisplayLink刷帧定时器,默认是每秒刷新60次
        //该定时器创建后,默认是不会执行的,需要把它加载到消息循环中
        CADisplayLink *display = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateImage)];
        [display addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    }
    return self;
}

- (void)updateImage{
    //调用此方法重绘画面
    [self setNeedsDisplay];
}

- (void)awakeFromNib{
    [super awakeFromNib];
    NSLog(@"awakeFromNib");
}

- (void)drawRect:(CGRect)rect{
    self.imagaeY += 5;
    if (self.imagaeY > rect.size.height) {
        self.imagaeY = 0;
    }
    UIImage *image = [UIImage imageNamed:@"雪花.png"];
    [image drawAtPoint:CGPointMake(0, self.imagaeY)];
    
}

第一个:

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];

说明: NSTimer一般用于定时的更新一些非界面上的数据,告诉多久调用一次

第二个:

 CADisplayLink *display= [CADisplayLink displayLinkWithTarget:self selector:@selector(updateImage)];
 [display addToRunLoop:[NSRunLoopmainRunLoop] forMode:NSDefaultRunLoopMode];
 说明: CADisplayLink刷帧,默认每秒刷新60次。该定时器创建之后,默认是不会执行的,需要把它加载到消息循环中

动态改变圆大小

two.gif
#import "CircleView.h"

@implementation CircleView

- (void)setRadius:(CGFloat)radius{
    _radius = radius;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //将当前View相对于父视图的中心坐标转换为相对于自己坐标系的中心点
    CGPoint center = self.center;
    CGPoint newPoint = [self convertPoint:center fromView:self.superview];
    CGContextAddArc(ctx, newPoint.x, newPoint.y, self.radius, 0, 2*M_PI, 0);
    [[UIColor redColor]setFill];
    CGContextFillPath(ctx);
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.radius = 20;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容

  • 问答 1. 块级元素和行内元素分别有哪些?动手测试并列出4条以上的特性区别 块级元素:div h1 h2 h3 h...
    cheneyzhangch阅读 106评论 0 0
  • 临近暑期,想着在暑假找一份Python爬虫的实习。刚好在一个Python群看到一个前辈发同花顺招聘信息,一来二去,...
    mashaz阅读 2,193评论 2 0
  • 童年里小麻花最爱的就是那些甜甜的糖果,每次吃到一颗,都会开心到极点;长大后成为妈妈,我自然知道,糖吃多了会对牙齿不...
    萌煮辅食阅读 471评论 0 1
  • 对门中年妇女在对丈夫吵叫, 窗外东南方向有小伙子在兴奋的嚎叫。 楼下有路人经过的谈笑, 我像一只埋在泥里的小青蛙不...
    违心运动阅读 236评论 0 0