Nick Weaver
Nick Weaver

Reputation: 47241

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

Upvotes: 13

Views: 3161

Answers (2)

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

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);
}

Upvotes: 28

Ajay Sharma
Ajay Sharma

Reputation: 4517

I think you could try using

myButton.layer.shadowOffset = CGSizeMake(-12.0, -12.0);

to

myButton.layer.shadowOffset = CGSizeMake(12.0, 12.0);

Just try using this, if it works.Either you need to set the shadow with Trial & Error method. This is just a suggestion or a trick if could solve your problem.

Upvotes: 0

Related Questions