iOS在标签上方画一条线

时间:2013-10-11 16:07:51

标签: ios quartz-2d

我认为我有一个标签。现在我想在标签上方画一条线,这意味着你可以看到标签在线下。

到目前为止,我可以使用quartz2D绘制一条线但总是在标签下面。有什么方法可以解决我的问题吗?

3 个答案:

答案 0 :(得分:3)

您可以像这样创建CAShapeLayer

CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.frame = self.label.bounds;
lineLayer.strokeColor = [UIColor redColor].CGColor;

CGRect rect = CGRectMake(0, CGRectGetMidY(lineLayer.bounds), lineLayer.bounds.size.width, 2);
lineLayer.path = [UIBezierPath bezierPathWithRect:rect].CGPath;

然后将其添加到UILabel,如下所示:

[self.label.layer addSublayer:lineLayer];

答案 1 :(得分:1)

老实说,最简单的方法是创建一个名为line@2x.png的2x2像素图像,底部2像素为黑色,顶部2为透明,然后将其用作图像视图的背景图像。通过将图像视图用作图案图像,将图像视图拉伸到所需的任何宽度。 1x图像应为1x1px,全黑。

UIView *lineView = [[UIView alloc] initWithFrame:frame]; // Whatever frame the line needs

// Add the line image as a pattern
UIColor *patternColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"line.png"]];
lineView.backgroundColor = patternColor;
[self.view addSubview:lineView];

答案 2 :(得分:0)

如果这是一个你会经常使用的标签,你可以创建一个UILabel的子类并覆盖drawRect函数。

- (void) drawRect:(CGRect)r
{
    [super drawRect:r];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineWidth(context, 1.0);
    CGContextMoveToPoint(context, 1.0, 1.0);
    CGContextAddLineToPoint(context, self.bounds.size.width - 1.0, 1.0);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

这里的优点是该行将“烘焙”到视图中,并且只能绘制一次。其他方法,如CAShapeLayer或UIView将在每一帧重新渲染。

对于奖励积分,您可以制作颜色和线宽属性:)

相关问题