UIImageView shadow and aspect-filling together
Asked Answered
R

1

8

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?

Rosio answered 25/2, 2014 at 11:2 Comment(0)
L
2

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.

Liftoff answered 20/3, 2014 at 12:54 Comment(1)
Nice solution, but I actually need to have interaction. It will be an effect for dragging a view (with the visual cue of that dragged being being "over" the others via shadow)Evocator

© 2022 - 2024 — McMap. All rights reserved.