Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawRect not getting called for UIImageView

I have a UIImageView in my IB and I created a subclass of UIImageView with one method drawRect:

@implementation UIImageViewLine

- (void)drawRect:(CGRect)rect
{
    NSLog(@"CALLED");
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);
    CGContextMoveToPoint(context, 0, 0); 
    CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height);
    CGContextStrokePath(context);

}

@end

I have changed the class of the UIImageView to this subclass, however the drawRect is never called. Any idea why?

like image 817
adit Avatar asked Feb 22 '12 23:02

adit


1 Answers

The UIImageView doesn't call drawRect when subclassed.

From the documentation:

The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.

You can simply replace the UIImageView by a normal UIView and draw the image and your custom drawings in the UIView's drawRect method or in child layers.

like image 186
sch Avatar answered Oct 10 '22 12:10

sch