自定义UIView的边框绘图不流畅

时间:2011-09-08 14:38:35

标签: ios quartz-graphics

我正在尝试使用以下代码绘制一个简单的语音气泡:

@implementation SpeechBubbleView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
       self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

   CGPoint triangleHeadPoint = CGPointMake(0, rect.size.height/2.0);
   float triangleHeight = 5;
   float triangleWidth = 10;

   float maxX = rect.size.width;
   float minX = 0.0;
   float maxY = rect.size.height;
   float minY = 0.0;

   float archTangentLine = 6.0;
   float archRadius = archTangentLine;

   float strokeWidth = 1.0;

   CGContextRef context = UIGraphicsGetCurrentContext();

   CGContextSetLineWidth(context, strokeWidth);   

   CGContextBeginPath(context);

   float currentX = triangleHeadPoint.x;
   float currentY = triangleHeadPoint.y;
   CGContextMoveToPoint(context, currentX, currentY);

   currentX += triangleWidth;
   currentY += (triangleHeight / 2.0);
   CGContextAddLineToPoint(context, currentX, currentY);

   currentY = maxY - archTangentLine;
   CGContextAddLineToPoint(context, currentX, currentY);

   currentY += archTangentLine;
   CGContextAddArcToPoint(context, currentX, currentY, currentX + archTangentLine, currentY, archRadius);

   currentX = maxX - archTangentLine;
   CGContextAddLineToPoint(context, currentX, currentY);

   currentX += archTangentLine;
   CGContextAddArcToPoint(context, currentX, currentY, currentX, currentY - archTangentLine, archRadius);

   currentY = minY + archTangentLine;
   CGContextAddLineToPoint(context, currentX, currentY);

   currentY -= archTangentLine;
   CGContextAddArcToPoint(context, currentX, currentY, currentX - archTangentLine, currentY, archRadius);

   currentX = minX + triangleWidth + archTangentLine;
   CGContextAddLineToPoint(context, currentX, currentY);

   currentX -= archTangentLine;
   CGContextAddArcToPoint(context, currentX, currentY, currentX, currentY + archTangentLine, archRadius);

   currentY = triangleHeadPoint.y - (triangleHeight / 2.0);
   CGContextAddLineToPoint(context, currentX, currentY);

   CGContextClosePath(context);

   [[UIColor whiteColor] setFill];
   [[UIColor blackColor] setStroke];

   CGContextDrawPath(context, kCGPathFillStroke);
}

@end

此代码的结果如下(不那么漂亮)图像:

enter image description here

图纸并不像我预期的那样平滑,左侧边框比顶边,右边和底边宽,而且边角比相邻边线宽。

我将填充颜色更改为黑色只是为了检查,结果如我所料:

enter image description here

边框为什么宽度可变?有没有办法解决这个问题,并在视图周围有一个平滑的边框?

提前致谢。

1 个答案:

答案 0 :(得分:6)

为了将来参考,我找到了一种改善边框外观的方法,这将导致以下图片:

enter image description here

我只是使用函数CGContextSetLineWidth(context,0.2f)使边框宽度非常小(我使用了0.2f)。然后在图层中添加阴影,如下所示:

self.layer.shadowColor = [[UIColor blackColor] CGColor];
self.layer.shadowOffset = CGSizeMake(1.5f, 1.5f);
self.layer.shadowOpacity = 0.8f;
self.layer.shadowRadius = 1.0f;

就是这样!