如何正确补偿CGContextRef坐标系,使原点在左上角 [英] How to properly compensate CGContextRef coordinate system, so the origin is at the top left corner
问题描述
我正在尝试使用 CoreText 绘制文本.我有以下代码:
I'm trying to draw text using CoreText. I have the following code:
CGContextRef uiContext = UIGraphicsGetCurrentContext();
NSMutableDictionary<NSAttributedStringKey,id> *attributes = [NSMutableDictionary<NSAttributedStringKey,id> new];
[attributes setObject:UIColor.redColor forKey:NSForegroundColorAttributeName];
[attributes setObject:[UIFont systemFontOfSize:40] forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Str" attributes:attributes];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, nil, CGRectMake(0, 50, attrString.size.width, attrString.size.height));
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil);
CTFrameDraw(frame, uiContext);
使用上面的代码,文本被正确放置,但在 y 方向上是镜像的
With the above code, text is placed properly, but is mirrored across y-direction
所以,我尝试应用翻译和缩放转换,这对文本有帮助,但现在它被放置在左下角,这不是所需的行为.
So, I tried to apply translate and scale transformation, which helped with text, but now it's placed at to bottom left corner, which isn't the desired behavior.
CGContextSetTextMatrix(uiContext, CGAffineTransformIdentity);
CGContextTranslateCTM(uiContext, 0.0, self.bounds.size.height);
CGContextScaleCTM(uiContext, 1.0, -1.0);
有什么想法我在这里遗漏了吗?谢谢.
Is there any ideas what am I missing here? Thanks.
推荐答案
这行 y 原点的 50 值从何而来?
Where does this 50 value for the y origin come from on this line?
CGPathAddRect(path, nil, CGRectMake(0, 50, attrString.size.width, attrString.size.height));
如果您从左下角的 y 坐标开始,该 50 值将从该位置开始绘制 y 原点 50 的路径.
If you're starting from the lower left y coordinate, that 50 value will start the path drawing y origin 50 up from that.
您应该能够通过使用容器视图的高度(您要将文本绘制到其中)减去 attrString.size.height 来调整 y 原点以从顶部偏移.
You should be able to adjust the y origin to be offset from the top by using the container view's height (that you'd like to draw the text into) minus the attrString.size.height.
这是一个示例,说明如果您正在绘制自定义视图的子类'drawRect:rect
:
Here's an example of what it might look like if you are doing the drawing a custom view's subclass' drawRect:rect
:
CGPathAddRect(path, nil, CGRectMake(0, rect.size.height - attrString.size.height, attrString.size.width, attrString.size.height));
结果如下:
这篇关于如何正确补偿CGContextRef坐标系,使原点在左上角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!