首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >与CGContextAddLineToPoint和CGContextSetLineWidth划清界限

与CGContextAddLineToPoint和CGContextSetLineWidth划清界限
EN

Stack Overflow用户
提问于 2012-10-14 10:21:15
回答 2查看 14.7K关注 0票数 15

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

您可以看到两者之间的区别-红色线条(宽度= 1)比紫色/蓝色线条(宽度= 0.5)要细得多。

这是我如何绘制我的伪1.0宽度水平线:

代码语言:javascript
复制
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);

下面是同一视图的边框,这次使用1.0边框宽度:

代码语言:javascript
复制
UIView *myView = (UIView *)self;
CALayer *layer = myView.layer;
layer.borderColor = [UIColor redColor].CGColor;
layer.borderWidth = 1.0;

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-14 11:08:36

当您对路径进行描边时,该描边会跨越该路径。换句话说,路径位于笔划的中心。

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

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

代码语言:javascript
复制
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会更简单

代码语言:javascript
复制
CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor);
CGContextFillRect(ctx, CGRectMake(0, y, self.bounds.size.width, 0.5f));
票数 38
EN

Stack Overflow用户

发布于 2013-06-20 04:10:26

当不在整数上绘制时,需要关闭抗锯齿以获得一条细线。

代码语言:javascript
复制
CGContextSetShouldAntialias(ctx, NO)
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12878781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档