我正在我的iPhone应用程序中绘制自由手绘图,并在主视图中将UIImageView作为子视图。当我在视图上绘制线条时,它在主视图上工作正常,但是当我尝试在图像视图上绘制时,它无效。我使用下面的代码绘制线条:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if([appdel.drawtype isEqualToString:@"pen"])
{
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
img.image = nil;
return;
}
lastPoint = [touch locationInView:self.view];
lastPoint.y -= 20;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([appdel.drawtype isEqualToString:@"pen"])
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 20;
UIGraphicsBeginImageContext(self.view.frame.size);
[img.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
img.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([appdel.drawtype isEqualToString:@"pen"])
{
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2) {
img.image = nil;
return;
}
UIGraphicsBeginImageContext(self.view.frame.size);
[img.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFlush(UIGraphicsGetCurrentContext());
img.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
如何在UIImageView
图片上绘制线条?