gpt4 book ai didi

ios - 用 CGContextAddLineToPoint 和 CGContextSetLineWidth 画一条很细的线

转载 作者:IT王子 更新时间:2023-10-29 08:21:43 26 4
gpt4 key购买 nike

我想在 UIView 的 drawRect 方法中绘制一条细线宽度的线。我看到的 CGContextSetLineWidth 值为 0.5 的行与用于绘制边框 CALayer 的相同 1.0 宽度值不匹配。

您可以看到两者之间的区别 - 红线 (width = 1) 比紫/蓝线 (width = 0.5) 细很多。

Border drawn with CALayer

这是我绘制伪 1.0 宽度水平线的方法:

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor);
CGContextSetLineWidth(ctx, 0.5); // I expected a very thin line

CGContextMoveToPoint(ctx, 0, y);
CGContextAddLineToPoint(ctx, self.bounds.size.width, y);

CGContextStrokePath(ctx);

这是同一 View 的边框,这次使用 1.0 边框宽度:

UIView *myView = (UIView *)self;
CALayer *layer = myView.layer;
layer.borderColor = [UIColor redColor].CGColor;
layer.borderWidth = 1.0;

要绘制与 CALayer 版本宽度相同的自定义线条,我需要做哪些不同的事情?

最佳答案

当您描边一条路径时,描边横跨路径。换句话说,路径位于笔画的中心。

如果路径沿两个像素之间的边缘延伸,则描边将(部分)覆盖该边缘两侧的像素。线宽为 0.5 时,水平笔画将向路径上方的像素延伸 0.25 磅,向路径下方的像素延伸 0.25 磅。

你需要移动你的路径,这样它就不会沿着像素的边缘运行:

CGFloat lineWidth = 0.5f;
CGContextSetLineWidth(ctx, lineWidth);

// Move the path down by half of the line width so it doesn't straddle pixels.
CGContextMoveToPoint(ctx, 0, y + lineWidth * 0.5f);
CGContextAddLineToPoint(ctx, self.bounds.size.width, y + lineWidth * 0.5f);

但是因为你只是画一条水平线,所以使用CGContextFillRect会更简单:

CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor);
CGContextFillRect(ctx, CGRectMake(0, y, self.bounds.size.width, 0.5f));

关于ios - 用 CGContextAddLineToPoint 和 CGContextSetLineWidth 画一条很细的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12878781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com