簡體   English   中英

如何在UIView中繪制具有不同顏色的多個UIBezierPath

[英]How to draw multiple UIBezierPath with different colors in a UIView

我想在UIView中使用不同的筆觸和填充顏色繪制多個UIBezierPath。

這是代碼

- (void)drawRect:(CGRect)rect {

    context = UIGraphicsGetCurrentContext();

    [[UIColor grayColor] setFill]; 
    [[UIColor greenColor] setStroke];

    UIBezierPath *aPath = [[UIBezierPath alloc] init]; 
    [aPath moveToPoint:CGPointMake(227,34.25)];
    [aPath addLineToPoint:CGPointMake(298.25,34.75)];
    [aPath addLineToPoint:CGPointMake(298.5,82.5)];
    [aPath addLineToPoint:CGPointMake(251,83)];
    [aPath addLineToPoint:CGPointMake(251,67.5)];
    [aPath addLineToPoint:CGPointMake(227.25,66.75)];   
    [aPath closePath]; 
    aPath.lineWidth = 2;
    [aPath fill]; 
    [aPath stroke];

    UIBezierPath *aPath2 = [[UIBezierPath alloc] init];
    [aPath2 moveToPoint:CGPointMake(251.25,90.5)];
    [aPath2 addLineToPoint:CGPointMake(250.75,83.25)];
    [aPath2 addLineToPoint:CGPointMake(298.5,83)];
    [aPath2 addLineToPoint:CGPointMake(298.5,90.25)];
    [aPath2 closePath];
    aPath2.lineWidth = 2;
    [aPath2 fill]; 
    [aPath2 stroke];
    [paths addObject:aPath2];

問題是筆划和填充顏色是在當前上下文中設置的。 是否可以在同一CGContextRef中繪制不同顏色的不同UIBezierPath?

或者我必須在單獨的UIView中繪制每個UIBezierPath?

你應該添加

[desiredStrokeColor setStroke];
[desiredFillColor setFill];

表明這些是在此上下文中必須進一步使用的新顏色。 你應該在每次打電話之前這樣做

[aNewPath fill];
[aNewPath stroke];

以便用這些顏色繪制路徑。

無需為每個貝塞爾曲線路徑使用新視圖。

用這個

int count = 0;
for(UIBezierpath *_paths in pathArray)
{
   UIColor *_color = [delegate1.colorArray objectAtIndex:q];
   [_color setStroke];
   [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0]; 
   count++;
}

觸摸開始將您的路徑和顏色存儲在兩個數組中,並像上面一樣使用它們。

只需定義一個UIColor * setStroke; 在.h文件中並在調用[myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];之前設置此strokeColor對象[myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

 - (void)drawRect:(CGRect)rect
    {
        [strokeColor setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        for(UIBezierPath *_path in pathArray)
            [myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    #pragma mark - Touch Methods
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        myPath=[[UIBezierPath alloc]init];
        myPath.lineWidth = currentSliderValue;

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM