在drawRect中的矩形顶部添加UILabel或Words

时间:2013-08-14 14:48:01

标签: ios string uiview drawrect

您好我有一个自定义视图,使用覆盖drawRect方法,用于绘制图形的条形图,代码为:

- (void)drawRect:(CGRect)rect
{

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);

    UIColor *barColor = [UIColor colorWithRed:226.0/255.0 green:178.0/255.0 blue:39.0/255.0 alpha:1.0];

    CGContextSetFillColorWithColor(context, barColor.CGColor);
    CGContextAddRect(context, rect);

    CGContextFillPath(context);
}

如何在条形图的顶部绘制字符串?我想减小矩形的高度,并在矩形的顶部(减少高度)绘制具有白色的字符串(颜色与条的使用颜色不同)。

此致

1 个答案:

答案 0 :(得分:0)

CGPoint textPoint = CGPointMake((rect.size.width - textSize.width) / 2, 0);
CGContextShowTextAtPoint(context, textPoint.x, textPoint.y, text, strlen(text));
CGContextSetTextDrawingMode (context, kCGTextFillStroke);

计算textSize
textSize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]];