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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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