views:

1302

answers:

1

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;
}
+1  A: 

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];
Ben Gottlieb
I tried adding this code but I still end up with clipped shadows.
April
Am I doing something else wrong in adding the code as above? or is the layer suppose to be the shadow?
April
The layer is supposed to be the shadow. You did set clipsToBounds to NO still?
Ben Gottlieb
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.
April
Er I meant blur not blue LOL
April
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.
Ben Gottlieb