【问题标题】:iOS: Mixing Core Graphics draw path and UIKit draw text functionsiOS:混合 Core Graphics 绘制路径和 UIKit 绘制文本功能
【发布时间】:2013-07-24 11:08:07
【问题描述】:

我在 UIView 的扩展类的 drawrect 方法中使用以下上下文来绘制路径和字符串。

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);

绘制路径我使用

CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0f);
CGContextSetLineWidth(context, 1);
CGContextBeginPath(context);
CGContextMoveToPoint(context, origin.x, origin.y);
CGContextAddLineToPoint(context, currentX, origin.y);
......
CGContextStrokePath(context);

我使用绘制文本

CGContextSetLineWidth(context, 2.0);    
[self.title drawInRect:CGRectMake(100, 100, 200, 40) withFont:font];

我得到了正确的路径,但文本倒置了!如果我删除 CGContextScaleCTM 和 CGContextTranslateCTM 我会得到路径颠倒!请有人帮我解决这个问题。

【问题讨论】:

    标签: ios nsstring core-graphics drawrect


    【解决方案1】:

    在绘制路径之前保存您之前的上下文并在之后恢复它:

    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // save the original context
    CGContextSaveGState(context);
    
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -rect.size.height);
    
    // draw path
    
    // restore the context
    CGContextRestoreGState();
    
    // draw text
    

    应该这样做。

    【讨论】:

    • 我已经尝试过了,但在绘制文本之前保存上下文并在之后恢复它。它没有用。我还需要垂直对齐的文本,并且必须使用 Coregraphics 函数来绘制文本,而不是 UIKI 。
    【解决方案2】:

    我最终编写了以下代码。可以帮助别人!

    - (void)drawText:(NSString*)text context:(CGContextRef)context rect:(CGRect)rect verticle:(BOOL)verticle {
        CGAffineTransform translate = CGAffineTransformMakeTranslation(0, -rect.size.height);
        CGAffineTransform transform = translate;
    
        if(verticle) {
            CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI/2);
            transform = CGAffineTransformConcat(translate, rotation);
        }
    
        CGContextSetTextMatrix(context, transform);
        CGContextShowTextAtPoint(context, rect.origin.x, rect.origin.y, [text UTF8String], text.length);
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多