2011-11-22 403 views
0

您好想在我尝试着色的项目中选择颜色。 我是新来的,所以这可能是一个愚蠢的问题。我正在使用按钮来选择不同的颜色。但是,当按下按钮时,唯一发生的事情是绘制线条的最后一个像素变为所选颜色。在第一个标签下面的代码删除图纸和第二应该改变颜色为将要绘制的下一行...更改颜色

-(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; 
    } 
} 

回答

1

代码:

CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 

不reallydraw线因为行CGContextMoveToPoint的开始和行CGContextAddLineToPoint的末尾是相同的点。

几个百分点,更少的代码更好:

  1. 由具有目标为每个按钮消除switch语句。
  2. 拨打UIGraphicsGetCurrentContext()一次,并将其保存在var中,只是为了清楚。

实施例:

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);