How to properly compensate CGContextRef coordinate system, so the origin is at the top left corner

£可爱£侵袭症+ 提交于 2019-12-11 14:22:42

问题


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);

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.


回答1:


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));

If you're starting from the lower left y coordinate, that 50 value will start the path drawing y origin 50 up from that.

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.

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));

Which would result in this:




回答2:


How about this one:

swift:

   CGContextSetTextMatrix(uiContext, CGAffineTransform(a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: 0.0))

Objective c:

    CGContextSetTextMatrix(uiContext, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0));

To simple setting, do the following:

   CGPathAddRect(path,nil, CGRectMake(0, 0, attrString.size.width, 1.5 * attrString.size.height));

instead of:

     CGPathAddRect(path, nil, CGRectMake(0, 50, attrString.size.width, attrString.size.height));


来源:https://stackoverflow.com/questions/55799043/how-to-properly-compensate-cgcontextref-coordinate-system-so-the-origin-is-at-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!