【问题标题】:use coretext draw string layout error使用coretext绘制字符串布局错误
【发布时间】:2013-07-19 15:19:12
【问题描述】:

我的代码是:

- (void)drawRect:(CGRect)rect {

/* Define some defaults */
float padding = 0.0f;
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef) [UIFont systemFontOfSize:12].fontName, [UIFont systemFontOfSize:12].lineHeight, NULL);

/* Get the graphics context for drawing */
CGContextRef ctx = UIGraphicsGetCurrentContext();

/* Core Text Coordinate System is OSX style */
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

//CGRect textRect = CGRectMake(padding, padding, self.frame.size.width, self.frame.size.height);
CGRect textRect = CGRectMake(padding, padding, 100, 100);


/* Create a path to draw in and add our text path */
CGMutablePathRef pathToRenderIn = CGPathCreateMutable();
CGPathAddRect(pathToRenderIn, NULL, textRect);
NSLog(@"textRect:%@",NSStringFromCGRect(self.bounds));
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"hello world!"];
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTFontAttributeName, font);

/* Get a framesetter to draw the actual text */
CTFramesetterRef fs = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) attrString);
CTFrameRef frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, attrString.length), pathToRenderIn, NULL);

/* Draw the text */
CTFrameDraw(frame, ctx);

/* Release the stuff we used */
CFRelease(frame);
CFRelease(pathToRenderIn);
CFRelease(fs);

}

但是,看起来像这样: 如何使文本从左上角开始并且不修改文本框(宽度 = 100 和高度 = 100)?

xxxxxxxxxxxxx x x x x x x x x x x xtext... x x x xxxxxxxxxxxxx

【问题讨论】:

    标签: ios core-text


    【解决方案1】:

    只需在您的代码中更改以下内容:

    CGRect textRect = CGRectMake(padding, self.frame.size.height - 100, 100, 100);
    

    无需更改文本矩形的框架大小(根据您的需要),但我们需要更改框架原点的 y。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多