UIImageView shadow and aspect-filling together

I have a UIImageView from which I set the image dynamically (from a URL). Images may have arbitrary sizes / proportions. I set the contentMode to Aspect Fill and view the clipsToBounds layer on YES and it displays correctly. However, I also want to display the shadow under the image view. When I set the shadow at the image level, I need to set clipsToBounds to NO to display the shadow, which leads to the display of fragments of the image from the displayed image. How can I keep a constant image size (filled aspect) and turn on the shadow at the same time?

One option may include creating a graphical context and re-drawing the image in this context, getting the image with my desired aspect ratio and setting this image as the image of the image, but this extra processing / wasted CPU and GPU as well as normal time ( especially if I have a large number of images with large images).

Another option would be to create an empty view with the same size of my image, paste it under my view into my supervisor, bind it to my view dynamically using constraints, and enable shadow at that level of presentation. It also involves creating an extra shadow-only view. This is probably a better / more efficient solution than the first, but still extra work (on the processor).

Is there any parameter that does not require additional work, which can use both shadow and aspect under my condition?

+6
source share
1 answer

One solution that, in my opinion, is optimal compared to your second option is to

If you want to just show the image and not have any user interaction on it. You can use two instances of CALayer .

If you want user interaction to interact with it, then one UIView and one CALayer .

With two instances of CALayer β†’

  • Create two layers. One layer stores and displays your image using the mask ToBounds = YES. You set the image on this layer using its contents property .
  • And add a higher level as subLayer to the second CALayer, to which you add shadow and clipToBounds = YES.

Apple's above suggestion. In your own words β†’

If you need a shadow, but you also want to use border masking, you use two layers instead of one. Apply a mask to the layer containing your content, and then paste this layer into a second layer of the same size that has a shadow effect.

Check this link. And find the above term.

+1
source

All Articles