我正在尝试学习 CoreGraphics,但遇到了一个奇怪的行为。
我画了一个矩形,在里面画了给定数量的菱形,可以用不同的填充(空的、填充的和带条纹的)来绘制形状,我的绘制矩形函数如下所示:
- (void)drawRect:(CGRect)rect
{
UIBezierPath* roundedRect = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:9.0];
//don't draw where the round corners "cut" the rectangle
[roundedRect addClip];
//set a white background
[[UIColor whiteColor] setFill];
UIRectFill(self.bounds);
//set a black frame
[[UIColor darkGrayColor] setStroke];
[roundedRect stroke];
self.shade = STRIPED;
self.color = [UIColor greenColor];
self.number = 3;
rectOffset = self.bounds.size.width / (self.number * 2);
[self drawDiamondNumberOfTimes:self.number startOrigin:self.bounds.origin];
}
drawDiamondNumberOfTimes:startOrigin: 是一个递归函数,用于计算要在其中绘制形状的矩形,并使用描边绘制菱形边界
- (void) drawDiamondNumberOfTimes:(int) p_times startOrigin:(CGPoint) p_origin
{
if( p_times > 0)
{
CGRect drawArea;
drawArea.origin = CGPointMake(p_origin.x + rectOffset-shapeSize.width/2, self.bounds.size.height/4);
drawArea.size = shapeSize;
UIBezierPath *diamond = [[UIBezierPath alloc] init];
[diamond moveToPoint:CGPointMake(drawArea.origin.x, drawArea.origin.y+ shapeSize.height/2)];
[diamond addLineToPoint:CGPointMake(drawArea.origin.x+shapeSize.width/2, drawArea.origin.y)];
[diamond addLineToPoint:CGPointMake(drawArea.origin.x+shapeSize.width, drawArea.origin.y+ shapeSize.height/2)];
[diamond addLineToPoint:CGPointMake(drawArea.origin.x+shapeSize.width/2, drawArea.origin.y+ shapeSize.height)];
[diamond closePath];
[self.color setStroke];
[diamond stroke];
[self drawShadeOfDraw:diamond atRect:drawArea];
drawArea.origin.x += rectOffset + shapeSize.width/2;
[self drawDiamondNumberOfTimes:p_times-1 startOrigin:drawArea.origin ];
}
}
drawShadeOfDraw:atRect: 设置不同的填充,出现奇怪行为的地方。
使用空填充和实心填充时效果很好,但使用条纹时,如果我写 [p_symbol addClip],那么即使 self.number 设置为 2 或 3,我也会得到一个菱形条纹。如果没有 [p_symbol addClip],我会得到正确数量的菱形但是,当然,条纹遍布矩形,这里是 drawShadeOfDraw:atRect 的代码:
- (void)drawShadeOfDraw:(UIBezierPath*)p_symbol atRect:(CGRect)p_drawArea
{
switch (self.shade)
{
case STRIPED:
{
[p_symbol addClip];
for( int y = p_drawArea.origin.y; y < p_drawArea.origin.y+ p_drawArea.size.height; y+= 6)
{
[p_symbol moveToPoint:CGPointMake(p_drawArea.origin.x, y)];
[p_symbol addLineToPoint:CGPointMake(p_drawArea.origin.x+shapeSize.width, y)];
[self.color setStroke];
[p_symbol stroke];
}
break;
}
case SOLID:
{
[self.color setFill];
[p_symbol fill];
break;
}
default:
{
break;
}
}
}
以下是一些图片:
我究竟做错了什么?