简体   繁体   English

如何在-drawRect中绘制UILabel:?

[英]How to draw an UILabel in -drawRect:?

Must I also do all this crazy coordinate system conversion stuff here, or is an UILabel different from an UIImageView drawing in -drawRect: ? 我必须在这里做所有这些疯狂的坐标系转换,或者是UILabel与-drawRect中的UIImageView绘图不同:?

There's a method called - (void)drawTextInRect:(CGRect)rect for that. 有一个名为- (void)drawTextInRect:(CGRect)rect的方法。

BUT the documentation says: "You should not call this method directly. This method should only be overridden by subclasses that want to modify the default drawing behavior for the label's text." 但是文档说:“你不应该直接调用这个方法。这个方法只能由想要修改标签文本的默认绘图行为的子类覆盖。”

So? 所以? How to draw it then in -drawRect:? 如何在-drawRect中绘制它?

UILabel is different in that you don't need to manually draw text to alter the way it is presented. UILabel的不同之处在于您不需要手动绘制文本来改变它的呈现方式。 Subclassing UILabel and overriding -drawTextInRect: is the quickest way to alter the way a UILabel is rendered. 对UILabel进行子类化并重写-drawTextInRect:是改变UILabel渲染方式的最快方法。 For example, 例如,

- (void)drawTextInRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetShadowWithColor( context, shadowOffset, shadowRadius, [shadowColor CGColor] );   
    [super drawTextInRect:rect];
}

will add a shadow with a specific offset, radius, and color (as a UIColor instance) to any text that you draw in that UILabel. 将为您在该UILabel中绘制的任何文本添加具有特定偏移,半径和颜色(作为UIColor实例)的阴影。 For an example of this in action, see a project I put together for a recent class . 有关此操作的示例,请参阅我为最近的课程放在一起的项目

However, if what you are looking to do is just draw text within another view, Vladimir's answer is the way to go. 但是,如果你想要做的只是在另一个视图中绘制文本,弗拉基米尔的答案是要走的路。

If you perform custom drawing in your view you must not draw UILabel or another UI element but rather draw text itself. 如果在视图中执行自定义绘图,则不得绘制UILabel或其他UI元素,而是绘制文本本身。 NSString has several methods for drawing in current context (look at NSString's UIKit extension docs for more methods): NSString有几种在当前上下文中绘制的方法(有关更多方法,请查看NSString的UIKit扩展文档):

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font
- (CGSize)drawAtPoint:(CGPoint)point withFont:(UIFont *)font

Actually you can do it. 其实你可以做到。

Try this: 试试这个:

UILabel *lblRef = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
lblRef.text = [refs objectAtIndex:barCount];
lblRef.adjustsFontSizeToFitWidth = TRUE;
lblRef.adjustsLetterSpacingToFitWidth = TRUE;
lblRef.textColor = self.color;
[lblRef setTextAlignment:NSTextAlignmentCenter];
lblRef.backgroundColor = [UIColor clearColor];
[self addSubview:lblRef];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM