I have a label in my view. Now I want to draw a line above the label, which means you can see the label is under the line.
So far I can draw a line using quartz2D but always under the label. Is there any way to solve my problems?
您可以创建一个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];
老实说,最简单的做法是创建一个名为 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];
如果这是一个你会经常使用的标签,你可以创建一个 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 将每帧重新渲染。
对于奖励积分,您可以制作颜色和线宽属性:)