I am trying to add a drop shadow to a UImageView
Asked Answered
D

1

3

I am trying to add a drop shadow to a UIImage view. I get a shadow but it is clipped to the edges of the image view and I am not sure why since I correctly set the uiimageview.clipsToBounds to NO. Below is the code:

-(void)addShadow
{
   UIGraphicsBeginImageContext(self.frame.size);
   CGContextRef myContext =  UIGraphicsGetCurrentContext();
   float           myColorValues[] = {0, 0, 0, darkness};// 3
   CGColorRef      myColor;// 4
   CGColorSpaceRef myColorSpace;
   CGContextSaveGState(myContext);// 6

   myColorSpace = CGColorSpaceCreateDeviceRGB ();// 9
   myColor = CGColorCreate (myColorSpace, myColorValues);// 10
   CGContextSetShadowWithColor (myContext, myShadowOffset, spread, myColor);// 11
   // Your drawing code here// 12
   // CGContextDrawImage(myContext, rotatingView.frame,imgRef);

   rotatingView.clipsToBounds = NO;
   [rotatingView.image drawInRect:rotatingView.frame
                        blendMode:kCGBlendModeNormal alpha:.5];
   CGColorRelease (myColor);// 13
   CGColorSpaceRelease (myColorSpace); // 14

   UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
   CGContextRestoreGState(myContext);
   UIGraphicsEndImageContext();
   rotatingView.image = imageCopy;
}
Drury answered 21/12, 2009 at 22:36 Comment(0)
F
2

I believe the CGContextRef you're passed also has clipping set, to prevent basically this exact behavior. You might want to try just adding a CALayer:

CALayer                         *layer = [CALayer layer];
CGRect                          bounds = self.bounds;

layer.bounds = bounds;
layer.position = CGPointMake(bounds.size.width / 2 + 5, bounds.size.height / 2 + 5);
layer.backgroundColor = [UIColor colorWithWhite: 0.10 alpha: 0.75].CGColor;
layer.zPosition = -5;

[self.layer addSublayer: layer];
Fox answered 21/12, 2009 at 23:5 Comment(6)
I tried adding this code but I still end up with clipped shadows.Drury
Am I doing something else wrong in adding the code as above? or is the layer suppose to be the shadow?Drury
The layer is supposed to be the shadow. You did set clipsToBounds to NO still?Fox
Ah I see. clipstobounds is set to no. The problem with the layer is that it produces a square shadow with no blue, under a UIImage with any given shape. I was trying to apply the shadow directly to the UIImage.Drury
ah, there's no easy way to do this. You'll basically have to do a custom shadow, and while there are several ways to do it, none of 'em are trivial to implement.Fox
make sure you #import "QuartzCore/CALayer.h"Unroll

© 2022 - 2024 — McMap. All rights reserved.