【问题标题】:iOS Draw a line above labeliOS 在标签上方画一条线
【发布时间】:2013-10-11 16:07:50
【问题描述】:

我认为我有一个标签。现在我想在标签上方画一条线,也就是说你可以看到标签在这条线的下方。

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

【问题讨论】:

  • 发布您的代码,以便我们为您提供帮助。
  • 你可以制作一个高两点的 UIView。
  • 当您说“在标签下”时,您的意思是标签遮住了线条(在这种情况下,如果您将标签的背景颜色更改为清除)?或者你是说你画的线的y坐标是这样的,它出现在标签的底部而不是它的顶部?

标签: ios quartz-2d


【解决方案1】:

您可以像这样创建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];

【讨论】:

    【解决方案2】:

    说实话,最简单的做法是创建一个名为 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];
    

    【讨论】:

    • 为什么要使用图片?只需将lineViewbackgroundColor 设置为您需要的任何线条颜色,并使lineView 只有一两个点高。
    • 是的,这是一种解决方案。
    • @rmaddy 使用图像,您可以在 Retina 显示屏上制作一条 1 像素的细线,而不必处理额外的屏幕比例条件。
    【解决方案3】:

    如果这是一个你会经常使用的标签,你可以创建一个 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 将每帧重新渲染。

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

    【讨论】:

      猜你喜欢
      • 2012-04-20
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      相关资源
      最近更新 更多