Question

In my project I need to use AsyncImageView to load images. I also want those images to be circular. The images appear in table views mostly, so I couldn't use roudned corners on the AsyncImageView's layer, because that had very, very negative effects on the performance of the app.

So what I decided to do is to create a subclass of AsyncImageView (because I needed the original non-circular AsyncImageView for other views in my project), called RoundedAsyncImageView, in which I only implemented the drawRect method like this:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:17].CGPath;
    CGContextAddPath(ctx, clippath);
    CGContextClip(ctx);
    [self.image drawInRect:rect];
    CGContextRestoreGState(ctx);
}

I have xib's for the cells in which this circular image should appear, created with IB. So I just changed the custom class of the UIImageView element to RoundedAsyncImageView and the IBOutlets of the image view to RoundedAsyncImageView. The problem now is that drawRect is not getting called. Any ideas why?

EDIT: I read that UIImageView subclasses don't call drawRect, and that I should simply draw the image in a regular UIView subclass. Problem is, I can't actually do that, as I need the AsyncImageView's functionality for asynchronously loading images. Is there any way to do this?

Was it helpful?

Solution

DrawRect method on UIImageView is slightly different than UIView

The view still has a CALayer, but the layer doesn’t allocate a backing store. Instead it uses a CGImageRef as its contents and the render server will draw that image’s bits into the frame buffer.

In this case, there’s no drawing going on. We’re simply passing bitmap data in form of an image to the UIImageView.

refer to this article Getting Pixels onto the Screen,And as my experience,that's why you can't get your imageView clip method worked.

Here is my solution:

  1. Instead of creating a subclass of AsyncImageView, create a subClass of UIView.
  2. Add AsyncImageView , which means your subClass become a wrapper view of AsyncImageView.
  3. Implement the clip method in drawRect, and let asyncImageView handle it's content changes.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top