手动图形的绘制

最近在学习一些动画的效果,其中有一个功能 可以手动绘制图像,比如 画板的实现。

在了解其实现原理之后实现起来还是比较简单的

代码如下:

@interface DrawView : UIView

@end


//
//  DrawView.m
//  QuarteCore
//
//  Created by HAOZO.MAC on 15/4/14.
//  Copyright (c) 2015年 HAOZO.MAC. All rights reserved.
//

#import "DrawView.h"

@interface DrawView ()
@property(nonatomic,strong)NSMutableArray *arrays;
@property(assign,nonatomic)CGMutablePathRef drawPath;
@end
@implementation DrawView

// 每次都是完整的绘制视图中需要绘制部分中的内容
- (void)drawRect:(CGRect)rect {
    CGContextRef context=UIGraphicsGetCurrentContext();
    [self drawView:context];
}

-(void)drawView:(CGContextRef)context{
//    CGContextMoveToPoint(context, self.preLocation.x, self.preLocation.y);
//    CGContextAddLineToPoint(context, self.location.x, self.location.y);
    
    //  首先将数组中的路径全部绘制出来
    for (UIBezierPath *path in self.arrays) {
        CGContextAddPath(context, path.CGPath);
        
        [[UIColor redColor]set];
        CGContextSetLineWidth(context, 10.0f);
        CGContextSetLineCap(context, kCGLineCapRound);
        
        CGContextDrawPath(context, kCGPathStroke);
    }
    
    CGContextAddPath(context, self.drawPath);
    
    [[UIColor redColor]set];
    CGContextSetLineWidth(context, 30.0f);
    CGContextSetLineCap(context, kCGLineCapRound);
    
    CGContextDrawPath(context, kCGPathStroke);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    UITouch *touch=[touches anyObject];
    CGPoint point=[touch locationInView:self];
    
    self.drawPath=CGPathCreateMutable();
    CGPathMoveToPoint(self.drawPath, NULL, point.x, point.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    // 可以获取到用户当前触摸到的点
    UITouch *touch=[touches anyObject];
    CGPoint point=[touch locationInView:self];
    
    // 添加到路径中
    CGPathAddLineToPoint(self.drawPath, NULL, point.x, point.y);
    [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    // 一笔画完,将完整的路径添加到路径数组中
    if (!self.arrays) {
        self.arrays=[[NSMutableArray alloc]init];
    }
    UIBezierPath *bezier=[UIBezierPath bezierPathWithCGPath:self.drawPath];
    
    // 需要记录当前绘制路径的颜色和线宽  可以自定义一个类来封装处理
    [self.arrays addObject:bezier];
    
    CGPathRelease(self.drawPath);
}
@end


==================

调用:

    DrawView *draw=[[DrawView alloc]initWithFrame:self.view.bounds];
    draw.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:draw];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值