本文介绍了用CGContext绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过 touchesMove:
方法画线。
I'm trying to draw lines through touchesMove:
method.
下面是我的 touchesMoved:
。
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// context setting
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, 2.0);
CGContextSetRGBStrokeColor(context, 255, 0, 0, 0.5);
CGContextSetBlendMode(context, kCGBlendModeNormal);
// drawing
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
CGContextFlush(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
调用 touchesMoved:
;但是,屏幕上什么都没有显示。
The touchesMoved:
is invoked; However nothing is shown on the screen.
我丢失了什么?
已添加 >
self是UIImageView的子类。
self is a subclass of UIImageView.
推荐答案
好,我发现了为什么它不起作用。我在每个触摸移动事件中都创建了 CGContext
。我将 UIGraphicsBeginImageContext(self.frame.size);
行移至 init
方法和 UIGraphicsEndImageContext ();
到 dealloc
。
OK, I found why it wasn't working. I created CGContext
every touch move event. I moved the line UIGraphicsBeginImageContext(self.frame.size);
to init
method and UIGraphicsEndImageContext();
to dealloc
.
这是我绘制代码的方式。
Here's the code how I drawing.
static CGPoint lastPoint;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch_ = [touches anyObject];
CGPoint point_ = [touch_ locationInView:self];
lastPoint = point_;
CGContextRef context = UIGraphicsGetCurrentContext();
// context setting
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, 2.0);
CGContextSetRGBStrokeColor(context, 255, 0, 0, 0.5);
CGContextSetBlendMode(context, kCGBlendModeNormal);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
lastPoint = CGPointZero;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
CGContextFlush(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
lastPoint = currentPoint;
}
这篇关于用CGContext绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!