我想在UIView的drawRect方法中绘制一条非常细的线条。我看到的CGContextSetLineWidth值为0.5的线条与用于绘制边框CALayer的1.0宽度值不匹配。
您可以看到两者之间的区别-红色线条(宽度= 1)比紫色/蓝色线条(宽度= 0.5)要细得多。
这是我如何绘制我的伪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);
下面是同一视图的边框,这次使用1.0边框宽度:
UIView *myView = (UIView *)self;
CALayer *layer = myView.layer;
layer.borderColor = [UIColor redColor].CGColor;
layer.borderWidth = 1.0;
要绘制与CALayer版本相同宽度的自定义线条,我需要做哪些不同的操作?
发布于 2012-10-14 11:08:36
当您对路径进行描边时,该描边会跨越该路径。换句话说,路径位于笔划的中心。
如果路径沿着两个像素之间的边缘运行,则笔划将(部分)覆盖该边缘两侧的像素。线宽为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));
发布于 2013-06-20 04:10:26
当不在整数上绘制时,需要关闭抗锯齿以获得一条细线。
CGContextSetShouldAntialias(ctx, NO)
https://stackoverflow.com/questions/12878781
复制相似问题