使用NSString,如何编目新接口以替换DrawInRect

时间:2013-12-05 09:10:19

标签: nsstring catalog drawinrect

我写了一个接口“myDrawInRect”来替换NSString中的原始“drawInRect”。

代码如下:

.h文件:

@interface NSString(TextDrawing)

-(CGSize) myDrawInRect:(CGRect)rect withFont:(UIFont *)font textColor:(UIColor*)textColor
         lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment;
@end

.m文件:

@interface NSString(TextDrawing)

-(CGSize) myDrawInRect:(CGRect)rect withFont:(UIFont *)font textColor:(UIColor*)textColor
         lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment
{
    CGFloat screen_scale = [UIScreen mainScreen].scale;
    CGContextRef bitmapContext = CreateBitmapContext( rect.size.width * screen_scale, rect.size.height * screen_scale );

    /* ... some code to draw the bitmapContext; */

    CGImageRef image = CGBitmapContextCreateImage( bitmapContext );

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM( context, 1.0f, -1.0f );
    CGContextTranslateCTM( context, 0.0f, -CGRectGetHeight(realRect) );
    CGContextDrawImage( context, rect, image );

    CGContextRelease( bitmapContext );
    CGImageRelease( myImage );
}

@end

我在UILabel drawInRect中调用了myDrawInRect,但我在标签上看不到任何内容。 任何人都可以建议吗?谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

CGImageRef image = CGBitmapContextCreateImage( bitmapContext );

CGContextRef context = UIGraphicsGetCurrentContext();

// MODIFY AND ADD FOLLOWING LINES
CGContextTranslateCTM( context, 0.0f, CGRectGetMaxY(realRect)*2 );
CGContextScaleCTM( context, 1.0f, -1.0f );

CGContextDrawImage( context, rect, image );

CGContextScaleCTM( context, 1.0f, -1.0f );
CGContextTranslateCTM( context, 0.0f, -CGRectGetMaxY(realRect)*2 );
// MODIFY UPTO THIS PONIT

CGContextRelease( bitmapContext );
CGImageRelease( myImage );