2013-07-24 79 views
1

我在UIView的擴展類的drawrect方法中使用下面的上下文來繪製路徑和字符串。iOS:混合核心圖形繪製路徑和UIKit繪製文本函數

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,我會得到路徑!有人可以幫我解決這個請。

回答

1

我最終寫了下面的代碼。可以幫助別人!

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

}

2

繪製你的路徑之前,保存以前的上下文並隨後將其還原:

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 

應該做到這一點。

+0

我繪製文本後恢復之前已經試過,但保存環境。它沒有工作。我還需要垂直對齊的文本,並且不得不使用Coregraphics函數繪製文本而不是UIKIts文本。 – applefreak