Reputation: 2059
How to draw text on imageview using coregraphics in iphone
Upvotes: 7
Views: 9790
Reputation: 1418
TextImageView.h
@interface TextImageView : UIView
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *text;
@end
TextImageView.m
@implementation TextImageView
- (void)drawRect:(CGRect)rect
{
[self.image drawInRect:self.bounds];
[self.text drawInRect:self.bounds
withAttributes:@{}];
}
@end
The method in the accepted answer has been deprecated. The method that you would want to use instead is - [NSString drawInRect:withAttributes:]
.
You are supposed to call this method from within the drawRect:
method of a UIView
subclass, but if you subclass UIImageView
, drawRect:
will never be called. (From the docs: "UIImageView does not call the drawRect: method of its subclasses.")
So, you really can't draw text on a UIImageView
, but you can subclass UIView
and have it draw an image with text on top as proposed above.
Upvotes: 0
Reputation: 10621
Either use a UILabel over your imageView or draw a string in the current graphics context with
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
Upvotes: 25