代码之家  ›  专栏  ›  技术社区  ›  Ale Morales

UIView drawRect绘制错误宽度的线条

  •  5
  • Ale Morales  · 技术社区  · 15 年前

    我想在视图的底部加一条红线。

    我希望这条线是1px的。

    - (void)drawRect:(CGRect)rect {
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSaveGState(currentContext);
    CGContextSetRGBFillColor(currentContext, 0.0f, 0.0f, 0.0f, 1.0f);
    CGContextFillRect(currentContext, RECT(0, 0, rect.size.width, rect.size.height - 8));
    CGContextSetLineWidth(currentContext, 1);
    CGContextSetRGBStrokeColor(currentContext, 1.0f, 0.0f, 0.0f, 1.0f);
    CGContextBeginPath(currentContext);
    CGContextMoveToPoint(currentContext, 0, rect.size.height - 7);
    CGContextAddLineToPoint(currentContext, rect.size.width, rect.size.height - 7);
    CGContextStrokePath(currentContext);
    CGContextRestoreGState(currentContext);
    }
    

    画一条两倍高的线?

    3 回复  |  直到 13 年前
        1
  •  14
  •   David M.    15 年前

    积分坐标表示像素之间的中间位置,即,(0,0)位于左上角, 在左上像素的上方和左侧 之间

    根据 the documentation for CGContextSetLineWidth

    因此,为了得到一条清晰的像素线,你必须将坐标偏移半个像素 x rect.size.height - 7.5 而不是 - 7 .

    顺便说一句,画矩形的时候,用起来很方便 CGRectInset(rect, 0.5, 0.5)

        2
  •  1
  •   Codo    15 年前

    你用iphone4吗?iPhone4使用的坐标系比例因子为2。所以需要将线宽设置为0.5才能得到所需的。

    (坐标系是这样设置的,因此相同的代码在所有模型上产生相同的输出。)

        3
  •  0
  •   hotpaw2    15 年前