Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageView shadow and aspect-filling together

I have a UIImageView of which I'm setting the image dynamically (from a URL). The images may have arbitrary sizes/aspect ratios. I am setting contentMode to Aspect Fill and view's layer's clipsToBounds to YES, and it's displayed correctly. However, I also want to display shadow under the image view. When I set shadow on the image view's layer, I need to set clipsToBounds to NO for the shadow to display, which causes the bleeding portions of the image from the view to be displayed. How can I keep the image view size constant (aspect-filled) and enable shadow simultaneously?

One option may involve creating a graphics context and re-drawing the image into that context, getting an image with my desired aspect ratio and setting that image as my image view's image, but that's extra processing/wasted both CPU/GPU and normal-world time (especially if I have a large number of image views with large images).

Another option may involve creating a blank view at the same size of my image view, inserting it below my view in my superview, attaching it to my view dynamically using constraints, and enabling shadow on that view's layer. That also involves creating an extra view just for shadow. Probably a better/more efficient solution than the first one, but still extra work (CPU-wise).

Is there any option that doesn't require extra work that can enable both shadow and aspect-fitting under my condition?

like image 381
Can Poyrazoğlu Avatar asked Feb 25 '14 11:02

Can Poyrazoğlu


1 Answers

One solution that i believe is optimal compared to your second option is,

If assuming you want to just show the image and not have any userInteraction on it.You can use two CALayer instances to achieve it.

If you want user Interaction also over it, then one UIView and one CALayer.

With two CALayer instances->

  • Create two layers. One layer storing and displaying your image with maskToBounds=YES. You set image to this layer using its contents property.
  • And add above layer as subLayer to second CALayer on which you will add shadow and clipToBounds=YES.

The above is suggested by Apple. In their own words->

If you want a shadow but also want to use bounds masking, you use two layers instead of one. Apply the mask to the layer containing your content and then embed that layer inside a second layer of the exact same size that has the shadow effect enabled.

Check this link. And search for above term.

like image 117
santhu Avatar answered Oct 18 '22 19:10

santhu