多个彩色贝塞尔曲线路径

时间:2012-06-01 07:20:00

标签: iphone objective-c ios cocoa-touch bezier

这是我的免费手绘图代码。但是当我绘制路径时,之前的路径就消失了。我无法弄清楚为什么会这样。有谁能够帮我。这是我的代码。

- (void)drawRect:(CGRect)rect
{

for (NSMutableDictionary *dictionary in pathArray) {

    UIBezierPath *_path = [dict objectForKey:@"Path"];

    UIColor *_colors = [dict objectForKey:@"Colors"];

    [_colors setStroke];

    _path.lineCapStyle = kCGLineCapRound;

    [_path stroke];

  }

}

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

isEdited=YES;

myPath=[[UIBezierPath alloc]init];

myPath.lineWidth=lineWidths;

CGPoint touchPoint = [[touches anyObject] locationInView:self];

UITouch *mytouch=[[touches allObjects] objectAtIndex:0];

[myPath moveToPoint:[mytouch locationInView:self]];

[myPath addLineToPoint:CGPointMake(touchPoint.x+1, touchPoint.y+1)];

[dict setObject:myPath forKey:@"Path"];

[dict setObject:brushPattern forKey:@"Colors"];

[pathArray addObject:dict];

[self setNeedsDisplay];


 }

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

UITouch *mytouch=[[touches allObjects] objectAtIndex:0];

[myPath addLineToPoint:[mytouch locationInView:self]];

[self setNeedsDisplay];

 }

2 个答案:

答案 0 :(得分:0)

每次发布​​时,您都应在myPath内创建dicttouchesBegan: localy。放弃他们全班的定义。

为了获得更简单(更快)的效果,您仍然可以使用全班级currentPathcurrentDict ivars用于touchesMoved:

编辑:代码看起来像这样:

//currentPath declared as an iVar of UIBezierPath* type
//currentDict declared as an iVar of NSMutableDictionary* type


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{    
    isEdited=YES;

    UIBezierPath *myPath=[[UIBezierPath alloc]init];  //locally created

    myPath.lineWidth=lineWidths;

    CGPoint touchPoint = [[touches anyObject] locationInView:self];

    UITouch *mytouch=[[touches allObjects] objectAtIndex:0];

    [myPath moveToPoint:[mytouch locationInView:self]];

    [myPath addLineToPoint:CGPointMake(touchPoint.x+1, touchPoint.y+1)];

    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; //locally created

    [dict setObject:myPath forKey:@"Path"];

    [dict setObject:brushPattern forKey:@"Colors"];

    [pathArray addObject:dict];

    [self setNeedsDisplay];

    currentPath = myPath;
    currentDict = dict;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
    [currentPath addLineToPoint:[mytouch locationInView:self]];
    [self setNeedsDisplay];
}

答案 1 :(得分:0)

1)在图纸视图中创建一个UIImage *currentImage实例变量。

2)在你的视图的drawRect方法中放入以下行:

[currentImage drawInRect:self.bounds];

3)在touchesEnded方法中输入以下代码:

        CGRect rect = self.bounds;
        UIGraphicsBeginImageContext(rect.size);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext(); 
        currentImage = tempImage;