iOS Quartz2D绘图使用篇

有兴趣可以贴代码看一下跑的效果,就不一一上图了

Quartz2D使用

  • drawRect:方法的使用
  • 常见图形的绘制:线条、多边形、圆
  • 绘图状态的设置:文字颜色、线宽等
  • 图形上下文状态的保存与恢复
  • 图形上下文栈

可以绘制:

  • 绘制图形 : 线条\三角形\矩形\圆\弧等

  • 绘制文字

  • 绘制\生成图片(图像)

  • 读取\生成PDF

  • 截图\裁剪图片

  • 自定义UI控件

较为复杂的UI空间无法直接使用, 那么我们可以通过quartz2D来绘制, 自定义view

常用的一些函数

1.获得图形上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

2.拼接路径(下面代码是搞一条线段)

CGContextMoveToPoint(ctx, 10, 10);

CGContextAddLineToPoint(ctx, 100, 100);

3.绘制路径

CGContextStrokePath(ctx); // CGContextFillPath(ctx);

•新建一个起点

void CGContextMoveToPoint(CGContextRef c, CGFloat x, CGFloat y)

•添加新的线段到某个点

void CGContextAddLineToPoint(CGContextRef c, CGFloat x, CGFloat y)

•添加一个矩形

void CGContextAddRect(CGContextRef c, CGRect rect)

•添加一个椭圆

void CGContextAddEllipseInRect(CGContextRef context, CGRect rect)

•添加一个圆弧

void CGContextAddArc(CGContextRef c, CGFloat x, CGFloat y,

CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)

•Mode参数决定绘制的模式

void CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode)

•绘制空心路径

void CGContextStrokePath(CGContextRef c)

•绘制实心路径

void CGContextFillPath(CGContextRef c)

提示:一般以CGContextDraw、CGContextStroke、CGContextFill开头的函数,都是用来绘制路径的

•将当前的上下文copy一份,保存到栈顶(那个栈叫做”图形上下文栈”)

void CGContextSaveGState(CGContextRef c)

•将栈顶的上下文出栈,替换掉当前的上下文

void CGContextRestoreGState(CGContextRef c)

•裁剪

CGContextClip(CGContextRef c);

栗子

画线段

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    // 1.获得图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.拼接图形(路径)
    // 设置线段宽度
    CGContextSetLineWidth(ctx, 10);
    
    // 设置线段头尾部的样式
    CGContextSetLineCap(ctx, kCGLineCapSquare);
    
    // 设置线段转折点的样式
    CGContextSetLineJoin(ctx, kCGLineJoinRound);
    
    /**  第1根线段  **/
    // 设置颜色
    CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
    // 设置一个起点
    CGContextMoveToPoint(ctx, 10, 10);
    // 添加一条线段到(100, 100)
    CGContextAddLineToPoint(ctx, 100, 100);
    
    // 渲染一次
    CGContextStrokePath(ctx);
    
    
    /**  第2根线段  **/
    // 设置颜色
    CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1);
    // 设置一个起点
    CGContextMoveToPoint(ctx, 200, 190);
    // 添加一条线段到(150, 40)
    CGContextAddLineToPoint(ctx, 150, 40);
    CGContextAddLineToPoint(ctx, 120, 60);
    
    
    // 3.渲染显示到view上面
    CGContextStrokePath(ctx);
}
image.png

画多边形

    /**
 *  画四边形
 */
void draw4Rect()
{
    // 1.获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.画矩形
    CGContextAddRect(ctx, CGRectMake(10, 10, 150, 100));
    
    // set : 同时设置为实心和空心颜色
    // setStroke : 设置空心颜色
    // setFill : 设置实心颜色
    [[UIColor whiteColor] set];
    
//    CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
    
    // 3.绘制图形
    CGContextFillPath(ctx);
}

/**
 *  画三角形
 */
void drawTriangle()
{
    // 1.获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.画三角形
    CGContextMoveToPoint(ctx, 0, 0);
    CGContextAddLineToPoint(ctx, 100, 100);
    CGContextAddLineToPoint(ctx, 150, 80);
    // 关闭路径(连接起点和最后一个点)
    CGContextClosePath(ctx);
    
    //
    CGContextSetRGBStrokeColor(ctx, 0, 1, 0, 1);
    
    // 3.绘制图形
    CGContextStrokePath(ctx);
}   

画圆相关


/**
 *  在view第一次显示到屏幕上的时候会调用一次
 */
- (void)drawRect:(CGRect)rect
{
//    // 1.获得上下文
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
//
//    // 2.画1/4圆
//    CGContextMoveToPoint(ctx, 100, 100);
//    CGContextAddLineToPoint(ctx, 100, 150);
//    CGContextAddArc(ctx, 100, 100, 50, -M_PI_2, M_PI, 1);
//    CGContextClosePath(ctx);
//
//    [[UIColor redColor] set];
//
//    // 3.显示所绘制的东西
//    CGContextFillPath(ctx);
    
    drawArc();
    drawCircle();
}

/**
 *  画圆弧
 */
void drawArc()
{
    // 1.获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.画圆弧
    // x\y : 圆心
    // radius : 半径
    // startAngle : 开始角度
    // endAngle : 结束角度
    // clockwise : 圆弧的伸展方向(0:顺时针, 1:逆时针)
    CGContextAddArc(ctx, 100, 100, 100, M_PI_2, M_PI, 0);
    
    
    // 3.显示所绘制的东西
    CGContextFillPath(ctx);
}

/**
 *  画圆
 */
void drawCircle()
{
    // 1.获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.画圆
    CGContextAddEllipseInRect(ctx, CGRectMake(50, 10, 100, 100));
    
    CGContextSetLineWidth(ctx, 10);
    
    // 3.显示所绘制的东西
    CGContextStrokePath(ctx);
}

画文字

/**
 *  画文字
 */
void drawText()
{
    // 1.获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 2.画矩形
    CGRect cubeRect = CGRectMake(50, 50, 100, 100);
    CGContextAddRect(ctx, cubeRect);
    // 3.显示所绘制的东西
    CGContextFillPath(ctx);
    
    
    
    // 4.画文字
    NSString *str = @"哈哈哈哈Good morning hello hi hi hi hi";
    //    [str drawAtPoint:CGPointZero withAttributes:nil];
    
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    // NSForegroundColorAttributeName : 文字颜色
    // NSFontAttributeName : 字体
    attrs[NSForegroundColorAttributeName] = [UIColor redColor];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    [str drawInRect:cubeRect withAttributes:attrs];
}

绘制小黄人


#define MJRadius 70
#define MJTopY 100
#define MJColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]

#import "MJHumanView.h"

@implementation MJHumanView

- (void)drawRect:(CGRect)rect
{
    // 1.上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 2.身体
    drawBody(ctx, rect);
    
    // 3.嘴(微笑)
    drawZui(ctx, rect);
    
    // 3.画眼睛
    drawLEyes(ctx, rect);
    drawREyes(ctx, rect);
}

/**
 *  眼睛
 */
void drawLEyes(CGContextRef ctx, CGRect rect)
{
    // 1.黑色绑带
    CGFloat startX = rect.size.width * 0.5 - MJRadius;
    CGFloat startY = MJTopY;
    CGContextMoveToPoint(ctx, startX, startY);
    CGFloat endX = startX + 2 * MJRadius;
    CGFloat endY = startY;
    CGContextAddLineToPoint(ctx, endX, endY);
    CGContextSetLineWidth(ctx, 15);
    [[UIColor blackColor] set];
    // 绘制线条
    CGContextStrokePath(ctx);
    
    // 2.最外圈的镜框
    [MJColor(61, 62, 66) set];
    CGFloat kuangRadius = MJRadius * 0.4;
    CGFloat kuangY = startY;
    CGFloat kuangX = rect.size.width * 0.5 - kuangRadius;
    CGContextAddArc(ctx, kuangX, kuangY, kuangRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    // 3.里面的白色框
    [[UIColor whiteColor] set];
    CGFloat whiteRadius = kuangRadius * 0.7;
    CGFloat whiteX = kuangX;
    CGFloat whiteY = kuangY;
    CGContextAddArc(ctx, whiteX, whiteY, whiteRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    //4,里边眼珠
    [MJColor(99, 58, 20) set];
    CGFloat zhuRadius = whiteRadius * 0.6;
    CGFloat zhuX = rect.size.width * 0.5 - zhuRadius * 2;
    CGFloat zhuY = whiteY;
    CGContextAddArc(ctx, zhuX, zhuY, zhuRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    //4,眼珠白色反光点
    [MJColor(228, 210, 210) set];
    CGFloat qiuRadius = zhuRadius * 0.2;
    CGFloat qiuX = zhuX + qiuRadius * 2;
    CGFloat qiuY = whiteY - qiuRadius;
    CGContextAddArc(ctx, qiuX, qiuY, qiuRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
}

void drawREyes(CGContextRef ctx, CGRect rect)
{    
    // 2.最外圈的镜框
    [MJColor(61, 62, 66) set];
    CGFloat kuangRadius = MJRadius * 0.4;
    CGFloat kuangY = MJTopY;
    CGFloat kuangX = rect.size.width * 0.5 + kuangRadius;
    CGContextAddArc(ctx, kuangX, kuangY, kuangRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    // 3.里面的白色框
    [[UIColor whiteColor] set];
    CGFloat whiteRadius = kuangRadius * 0.7;
    CGFloat whiteX = kuangX;
    CGFloat whiteY = kuangY;
    CGContextAddArc(ctx, whiteX, whiteY, whiteRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    //4,里边眼珠
    [MJColor(99, 58, 20) set];
    CGFloat zhuRadius = whiteRadius * 0.6;
    CGFloat zhuX = rect.size.width * 0.5 + zhuRadius * 2;
    CGFloat zhuY = whiteY;
    CGContextAddArc(ctx, zhuX, zhuY, zhuRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
    
    //4,眼珠白色反光点
    [MJColor(228, 210, 210) set];
    CGFloat qiuRadius = zhuRadius * 0.2;
    CGFloat qiuX = zhuX - qiuRadius * 2;
    CGFloat qiuY = whiteY - qiuRadius;
    CGContextAddArc(ctx, qiuX, qiuY, qiuRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx);
}

/**
 *  画嘴
 */
void drawZui(CGContextRef ctx, CGRect rect)
{
    // 中间的控制点
    CGFloat controlX = rect.size.width * 0.5;
    CGFloat controlY = rect.size.height * 0.4;
    
    // 当前点
    CGFloat marginX = 20;
    CGFloat marginY = 10;
    CGFloat currentX = controlX - marginX;
    CGFloat currentY = controlY - marginY;
    CGContextMoveToPoint(ctx, currentX, currentY);
    
    // 结束点
    CGFloat endX = controlX + marginX;
    CGFloat endY = currentY;
    
    // 贝塞尔曲线
    CGContextAddQuadCurveToPoint(ctx, controlX, controlY, endX, endY);
    
    // 设置颜色
    [[UIColor blackColor] set];
    
    // 渲染
    CGContextStrokePath(ctx);
}

/**
 *  画身体
 */
void drawBody(CGContextRef ctx, CGRect rect)
{
    // 上半圆
    CGFloat topX = rect.size.width * 0.5;
    CGFloat topY = MJTopY;
    CGFloat topRadius = MJRadius;
    CGContextAddArc(ctx, topX, topY, topRadius, 0, M_PI, 1);
    
    // 向下延伸
    CGFloat middleX = topX - topRadius;
    CGFloat middleH = 100; // 中间身体的高度
    CGFloat middleY = topY + middleH;
    CGContextAddLineToPoint(ctx, middleX, middleY);
    
    // 下半圆
    CGFloat bottomX = topX;
    CGFloat bottomY = middleY;
    CGFloat bottomRadius = topRadius;
    CGContextAddArc(ctx, bottomX, bottomY, bottomRadius, M_PI, 0, 1);
    
    // 合并路径
    CGContextClosePath(ctx);
    
    // 设置颜色
    [MJColor(252, 218, 0) set];
    
    // 利用填充方式画出之前的路径
    CGContextFillPath(ctx);
}

image.png

刷帧

拖动Slider改变值,控制图形变化

##viewController.m
@interface MJViewController ()
- (IBAction)sizeChange:(UISlider *)sender;
@property (weak, nonatomic) IBOutlet MJView *circleView;

@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sizeChange:(UISlider *)sender {
    self.circleView.radius = sender.value;
}
@end
    
##view.m
@implementation MJView

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

/**
 *  默认只会在view第一次显示的时候调用(只能由系统自动调用, 不能手动调用)
 */
- (void)drawRect:(CGRect)rect
{
    NSLog(@"drwract---%f", self.radius);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextAddArc(ctx, 125, 125, self.radius, 0, M_PI * 2, 0);
    
    CGContextFillPath(ctx);
}

@end
image.png

动画❄️飘落

#view.m
@implementation MSnowView

- (void)awakeFromNib
{
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    //    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(setNeedsDisplay) userInfo:nil repeats:YES];
}

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

模仿UIImageView

//场景,绘制图片,点击更换图片,重写方法一定要重写set方法
#viewControlle.m
@interface ViewController ()
@property (nonatomic, weak) DWImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    DWImageView *imageView = [[DWImageView alloc] init];

    imageView.image = [UIImage imageNamed:@"black.png"];
    imageView.frame = CGRectMake(50, 50, 200, 200);
    [self.view addSubview:imageView];
    self.imageView = imageView;
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:@"点击换图" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    btn.frame = CGRectMake(200, 200, 100, 50);
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void) btnClick{
    
    //如果不重写set方法, 那么替换将会失败
    self.imageView.image = [UIImage imageNamed:@"black2.png"];
}

- (void) imageViewUse {
    //    UIImageView *imageView = [[UIImageView alloc] init];
    //    imageView.image = [UIImage imageNamed:@"black.png"];
    //    imageView.frame = CGRectMake(50, 50, 200, 200);
    //    [self.view addSubview:imageView];
        
        //另一种初始化方式
        UIImage *image = [UIImage imageNamed:@"black.png"];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        //imageView.frame = CGRectMake(50, 50, 200, 200);   //initWithImage该方法可以不用设置大小,展示原画图大小
        
        CGRect imageFrame = imageView.frame;             //取出frame
        imageFrame.origin = CGPointMake(300, 300);       //设置原点
        imageView.frame = imageFrame;                    //重新赋值

        [self.view addSubview:imageView];
}
@end
    
#DWImageView.h
@interface DWImageView : UIView
@property (nonatomic, strong) UIImage *image;
@end

#DWImageView.m
@implementation DWImageView
//重写set方法
- (void)setImage:(UIImage *)image {
    _image = image;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [self.image drawInRect:rect];
}

@end

自定义UITextVIew,实现提示文字 placehoader

用UITextView实现类似UITextField的placehoader功能
viewController.m
@implementation ViewControllerTestTextView

- (void)viewDidLoad {
    [super viewDidLoad];
   
    DWPlaceholderTextView *textView = [[DWPlaceholderTextView alloc] initWithFrame:CGRectMake(20, 50, SCREEN.width-40, 100)];
    textView.backgroundColor = [UIColor blackColor];
    textView.textColor = [UIColor grayColor];
    textView.textAlignment = NSTextAlignmentCenter;
    textView.placeholder = @"ni hao al ";

    [self.view addSubview:textView];
}

@end

    
    
DWPlaceholderTextView.m
@implementation DWPlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置默认字体
        self.font = [UIFont systemFontOfSize:15];
        
        // 设置默认颜色
        self.placeholderColor = [UIColor grayColor];
        
        // 使用通知监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

- (void)textDidChange:(NSNotification *)note
{
    // 会重新调用drawRect:方法
    [self setNeedsDisplay];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 * 每次调用drawRect:方法,都会将以前画的东西清除掉
 */
- (void)drawRect:(CGRect)rect
{
    // 如果有文字,就直接返回,不需要画占位文字
    if (self.hasText) return;
    
    // 属性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    
    // 画文字
    rect.origin.x = 5;
    rect.origin.y = 8;
    rect.size.width -= 2 * rect.origin.x;
    [self.placeholder drawInRect:rect withAttributes:attrs];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self setNeedsDisplay];
}

#pragma mark - setter
- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    
    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    
    [self setNeedsDisplay];
}

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    
    [self setNeedsDisplay];
}

@end

水印

UIImage+water.h
@interface UIImage (water)
+ (instancetype)setWaterWithImage:(NSString *)bg logo:(NSString *)logo;
@end

    
UIImage+water.m
#import "UIImage+water.h"

    
@implementation UIImage (water)
+ (UIImage *)setWaterWithImage:(NSString *)bg logo:(NSString *)logo {

    UIImage *bgImage = [UIImage imageNamed:bg];
    
    //上下文: 基于位图, 所有东西绘制到这一张图片上
    /**void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
     * size: 新图尺寸
     * opaque:YES不透明。 NO透明
     */
    //1.创建一个位图
    UIGraphicsBeginImageContextWithOptions(bgImage.size, YES, 0.0);
    
    //2.画背景
    [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width, bgImage.size.height)];
    
    //3.画logo
    //x, y, w, h   scale, margin
    UIImage *waterImage = [UIImage imageNamed:logo];
    CGFloat scale = 0.2;
    CGFloat margin = 10;
    CGFloat waterW = waterImage.size.width * scale;
    CGFloat waterH = waterImage.size.height * scale;
    CGFloat waterX = bgImage.size.width - waterW - margin;
    CGFloat waterY = bgImage.size.height - waterH - margin;
    
    [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)];
    
    //4.获取图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    //5.结束上下文
    UIGraphicsEndImageContext();
    
    //7.压缩png格式的二进制数据
    NSData *data =UIImagePNGRepresentation(image);
    
    //8.写入文件
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"newimage.png"];
    [data writeToFile:path atomically:YES];

    return image;
}
@end

截图

viewController.m
//点击按钮截图 延迟一秒
- (IBAction)clip:(id)sender {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIImage *image = [UIImage screenShotImage:self.screenView];
        
        NSData *data = UIImagePNGRepresentation(image);
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"screen.png"];
       
        NSLog(@"%@", path);
       
        //4.写入文件
        [data writeToFile:path atomically:YES];
    });
}


UIImage+screenshot.h
+ (instancetype) screenShotImage:(UIView *)view;


UIImage+screenshot.m
#import "UIImage+screenshot.h"
@implementation UIImage (screenshot)
+ (UIImage *) screenShotImage:(UIView *)view {
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
   
    //2.将控制器的view渲染到上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctr];
   
    //3.取出图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   
    //5.结束上下文
    UIGraphicsEndImageContext();
   
    return image;
}

@end

裁减圆形头像带圆形边框

viewController.m
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    UIImage *newImage = [UIImage circleImageWithName:@"black.png" borderWidth:3 borderColor:[UIColor whiteColor]];
    self.imageView.image = newImage;
    
    NSData *data = UIImagePNGRepresentation(newImage);
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"new.png"];
    [data writeToFile:path atomically:YES];
}
    


UIImage+circle.h

@interface UIImage (circle)
+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;
@end
    
    
    
UIImage+circle.m
#import "UIImage+circle.h"

@implementation UIImage (circle)
+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
    // 1.加载原图
    UIImage *oldImage = [UIImage imageNamed:name];
    
    // 2.开启上下文
    CGFloat imageW = oldImage.size.height + 2 * borderWidth;
    CGFloat imageH = oldImage.size.height + 2 * borderWidth;
    CGSize imageSize = CGSizeMake(imageW, imageH);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    
    // 3.取得当前的上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 4.画边框(大圆)
    [borderColor set];
    CGFloat bigRadius = imageW * 0.5; // 大圆半径
    CGFloat centerX = bigRadius; // 圆心
    CGFloat centerY = bigRadius;
    CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx); // 画圆
    
    // 5.小圆
    CGFloat smallRadius = bigRadius - borderWidth;
    CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
    // 裁剪(后面画的东西才会受裁剪的影响)
    CGContextClip(ctx);
    
    // 6.画图
    [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
    
    // 7.取图
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 8.结束上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}
@end

图片拉伸

viewController.m
    
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *image = [UIImage imageNamed:@"black.png"];
    //设置view背景图片 过于占用内存不建议使用  该方法多张图片平铺
    //self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    
    //拉伸做法
    //1.获取上下文
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, YES);
    //2.画图
    [image drawInRect:self.view.bounds];
    //3.获取图片
    UIImage *newimage = UIGraphicsGetImageFromCurrentImageContext();
    //4.结束上下文
    UIGraphicsEndImageContext();
    //5.展示图片
    self.view.backgroundColor = [UIColor colorWithPatternImage:newimage];
}

添加横线

//给textView添加横线
viewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //开启上下文
    CGFloat rowW = self.view.frame.size.width;
    CGFloat rowH = 40;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(rowW, rowH), NO, 0.0);
    
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    
    //画矩形框
    [[UIColor redColor] set];
    CGContextAddRect(ctr, CGRectMake(0, 0, rowW, rowH));
    CGContextFillPath(ctr);  //填充
    //奇偶填充
    //CGContextEOFillPath(ctr);
    
    //画线
    [[UIColor blackColor] set];
    CGFloat lineWidth = 2;
    CGContextSetLineWidth(ctr, lineWidth);
    CGFloat dividerX = 10;
    CGFloat dividerY = rowH - lineWidth;
    CGContextMoveToPoint(ctr, dividerX, dividerY);  //画笔移动到该点开始画线
    CGContextAddLineToPoint(ctr, rowW - 10, dividerY);   //路径绘制
    CGContextStrokePath(ctr);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    //给某个view画线
    self.textView.backgroundColor = [UIColor colorWithPatternImage:newImage];
}

你可能感兴趣的:(iOS Quartz2D绘图使用篇)