开发者

How to draw an UILabel in -drawRect:?

开发者 https://www.devze.com 2022-12-27 17:46 出处:网络
Must I also do all this crazy coordinate system conversion stuff here, or is an UILabel different from an UIImageView drawing 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: ?

There's a method called - (void)drawTextInRect:(CGRect)rect for that.

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开发者_如何学JAVA then in -drawRect:?


UILabel is different in that you don't need to manually draw text to alter the way it is presented. Subclassing UILabel and overriding -drawTextInRect: is the quickest way to alter the way a UILabel is rendered. 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. 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. NSString has several methods for drawing in current context (look at NSString's UIKit extension docs for more methods):

- (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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号