xamarin.ios - 为什么这个 Core Graphics 绘图代码会生成不同的线宽?

标签 xamarin.ios core-graphics cgcontext

看图片。小矩形具有不同的线宽。指向大中心矩形的线较粗。以左上角为例:到线和左边比右边和底部细。 起初我以为这是一种视错觉,但事实并非如此。屏幕截图是在模拟器上以 100% 拍摄的。

enter image description here

下面用于绘制 View 的代码来自 UIView 子类的 DrawRect():

public override void Draw (RectangleF rect)
        {
            rect = this.Bounds;
            CGContext oCtx = UIGraphics.GetCurrentContext();
            oCtx.SetFillColor(UIColor.Clear.CGColor);
            oCtx.ClearRect(rect);

            oCtx.SetLineWidth(2f);

            oCtx.SetFillColor(this.BackgroundColor.CGColor);
            oCtx.SetStrokeColor(this.BackgroundColor.CGColor);
            oCtx.SetAlpha(this.Alpha);

            oCtx.AddRect(new RectangleF(rect.X + HANDLE_WIDTH * 0.5f, rect.Y + HANDLE_HEIGHT * 0.5f, rect.Width - HANDLE_WIDTH, rect.Height - HANDLE_HEIGHT));

            oCtx.FillPath();

            oCtx.SetAlpha(1f);
            oCtx.AddRect(new RectangleF(rect.X, rect.Y, HANDLE_WIDTH, HANDLE_HEIGHT));
            oCtx.AddRect(new RectangleF(rect.Right - HANDLE_WIDTH, rect.Y, HANDLE_WIDTH, HANDLE_HEIGHT));
            oCtx.AddRect(new RectangleF(rect.Right - HANDLE_WIDTH, rect.Bottom - HANDLE_HEIGHT, HANDLE_WIDTH, HANDLE_HEIGHT));
            oCtx.AddRect(new RectangleF(rect.X, rect.Bottom - HANDLE_HEIGHT, HANDLE_WIDTH, HANDLE_HEIGHT));

            oCtx.StrokePath();

#if DEBUG
            oCtx.SetAlpha(0.2f);
            oCtx.SetFillColor(UIColor.DarkGray.CGColor);
            oCtx.AddRect(this.GetMovableArea(rect));
            oCtx.FillPath();
#endif
        }

有人可以解释一下为什么笔划宽度不同吗?我也尝试使用 StrokeRect() 代替 - 相同的结果。我什至删除了所有绘图代码,除了左上角的矩形之外,没有任何更改。常量 HANDLE_HEIGHT 和 HANDLE_WIDTH 均设置为 20f。

最佳答案

这是由于 CoreGraphics 使用中心笔对齐,例如它将在您指定的线的两侧绘制像素。正如您所注意到的,将坐标引入线宽的一半即可修复它。

本文有一个示例,还讨论了 iOS 应用到线路的抗锯齿以及如何避免它。

http://www.raywenderlich.com/2033/core-graphics-101-lines-rectangles-and-gradients

In our case, the edge of the path is the rectangle we wish to fill. So when drawing a 1 >pixel line along that edge, half of the line (1/2 pixel) will be on the inside of the >rectangle, and the other half of the line (1/2 pixel) will be on the outside of the >rectangle.

But of course, since there’s no way to draw 1/2 a pixel, instead Core Graphics uses anti->aliasing to draw in both pixels, but just a lighter shade to give the appearance that it >is only a single pixel drawn.

我认为你无法在 CG 中更改此设置,这与 GDI+ 不同,在 GDI+ 中你可以设置笔对齐 http://msdn.microsoft.com/en-us/library/z62ath7a.aspx

关于xamarin.ios - 为什么这个 Core Graphics 绘图代码会生成不同的线宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11618254/

相关文章:

ios - 如何为 iPad 应用程序创建甘特图 View ?

ios - 单点触控远程控制事件不起作用

iphone - 如何将 UIView 渲染成两部分

iphone - 在 drawRect : 中使用 Core Graphics 绘制图像网格

iphone - UIImageView将图像过滤为纯色

ios - 在 iOS 中添加 PDF 页面

ios - 如何在 draw(_ rect : CGRect) in Swift 中使用不同的混合模式绘制 UILabel

c# - 背景图片 PCL xamarin forms iOS 放大

ios - iPhone 中的 UIDatePicker 大小调整

ios - 类似Apple Watch健身应用的渐变画环