Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I draw a rotated UIView with a shadow but without the shadow being rotated as well

I'd like the shadow applied correctly after rotation. This is my code:

myButton.transform = CGAffineTransformMakeRotation(M_PI / 180.0 * 90.0);

myButton.layer.shadowOffset = CGSizeMake(12.0, 12.0);
myButton.layer.shadowRadius = 2.0;
myButton.layer.shadowOpacity = 0.8;
myButton.layer.shadowColor = [UIColor blackColor].CGColor;

Without rotation the shadow looks fine:

enter image description here

But after rorating it by 90° the shadow is rotated as well:

enter image description here

Is there anything I can do about it without overriding the drawRect method and do low level drawing? Or maybe some method which corrects the shadowOffset with a given rotation angle? It's easy to correct the offset by hand for 90° so this is no option ;)

It should look like this:

enter image description here

Thanks in advance!

With help of Bartosz Ciechanowski this works now!

float angleInRadians = M_PI / 180.0 * -35.0;

myButton.transform = CGAffineTransformMakeRotation(angleInRadians);

myButton.layer.shadowOffset = [self correctedShadowOffsetForRotatedViewWithAngle:(angleInRadians) 
                                                          andInitialShadowOffset:CGSizeMake(12.0, 12.0)];
myButton.layer.shadowRadius = 2.0;
myButton.layer.shadowOpacity = 0.8;
myButton.layer.shadowColor = [UIColor blackColor].CGColor;

This results in:

enter image description here

instead of

enter image description here

like image 964
Nick Weaver Avatar asked Apr 25 '11 11:04

Nick Weaver


1 Answers

Assuming anAngle is in radians:

- (CGSize)correctedShadowOffsetForRotatedViewWithAngle:(CGFloat)anAngle 
                                andInitialShadowOffset:(CGSize)anOffset
{
    CGFloat x = anOffset.height*sinf(anAngle) + anOffset.width*cosf(anAngle);
    CGFloat y = anOffset.height*cosf(anAngle) - anOffset.width*sinf(anAngle);

    return CGSizeMake(x, y);
}
like image 117
Bartosz Ciechanowski Avatar answered Oct 21 '22 10:10

Bartosz Ciechanowski