Reputation: 1
Hi want to choose colors in a coloring project that I am trying out. I am new at this so this might be a silly question. I am using buttons to select different colors. But when the button is pressed the only thing that happens is that the last pixel of the line that was drawn changes to the selected color. In the code below the first tag erases the drawing and the second should change to color for the next line that will be drawn...
-(IBAction)buttonClicked:(UIButton *)sender {
switch (sender.tag)
{
case 1: {
drawImage.image = nil;
return;
}
//lastPoint.y -= 0;
break;
case 2: {
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 3.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 1.0, 2.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFlush(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
break;
default:
break;
}
}
Upvotes: 0
Views: 168
Reputation: 112857
The code:
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
does not reallydraw a line since the start of the line CGContextMoveToPoint
and the end of the line CGContextAddLineToPoint
are the same point.
A couple of points, less code is better:
UIGraphicsGetCurrentContext()
once and save it in a var, just for clarity.Example:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 3.0);
CGContextSetRGBStrokeColor(context, 0.0, 1.0, 2.0, 1.0);
CGContextMoveToPoint(context, firstPoint.x, firstPoint.y);
CGContextAddLineToPoint(context, lastPoint.x, lastPoint.y);
CGContextStrokePath(context);
Upvotes: 1