iOS绘图-简易绘图板(一)

2016-01-08  本文已影响570人  bonoCat

绘图在实际的使用中是非常多的,比如画线、画圈等,希望通过简单的例子来进行iOS相关动画的学习。

本文主要实现了一个简单的绘图板,具体效果显示如下:

效果图.gif

我们知道可以使用 Core Graphics 来进行线条的绘制

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(context, width);
CGContextSetStrokeColorWithColor(context, [color CGColor]);


CGContextMoveToPoint(context, model.startPoint.x, model.startPoint.y);
    
CGContextAddLineToPoint(context, point.x, point.y);


CGContextStrokePath(context);

接下来就要获取手势的开始、移动、停止的路径,在 ViewController 中,有以下方式可以获得:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

}

由于我们在 touchesMoved 的时候,需要在界面上显示移动路径,所以,在此时更新界面

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint touchPoint;

    UITouch *touch = [touches anyObject];

    if (touch) {
    
        touchPoint = [touch locationInView:self.imageView];
    
UIGraphicsBeginImageContext(self.imageView.frame.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

     CGContextSetLineWidth(context, width);
     
     CGContextSetStrokeColorWithColor(context, [color CGColor]);

///// 需要绘制 linePoints 所有数据

for (LineModel *model in self.linePoints)
{
    CGContextMoveToPoint(context, model.startPoint.x, model.startPoint.y);
    
    for (NSValue *value in model.linePoints)
    {
        CGPoint point = [value CGPointValue];
        
        CGContextAddLineToPoint(context, point.x, point.y);
        
    }

}

CGContextStrokePath(context);

UIGraphicsEndImageContext();
    
    }
}

这样就可以简单的实现绘图效果了,这里使用的是不断生成 image 来显示的,也可以在drawrect中来实现,但是图层就创建了一个绘制上下文,这个上下文需要的大小的内存可从这个算式得出:图层宽图层高4字节,宽高的单位均为像素。对于一个在Retina iPad上的全屏图层来说,这个内存量就是 204815264字节,相当于12MB内存,图层每次重绘的时候都需要重新抹掉内存然后重新分配。

具体Demo,在这里

上一篇下一篇

猜你喜欢

热点阅读