如何绘制带有阴影的旋转UIView,但也不会旋转阴影 [英] How can I draw a rotated UIView with a shadow but without the shadow being rotated as well

查看:191
本文介绍了如何绘制带有阴影的旋转UIView,但也不会旋转阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

旋转后我想正确应用阴影。这是我的代码:

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:

但是在漫游之后旋转阴影90°:

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

在没有覆盖drawRect方法并进行低级绘图的情况下,我能做些什么吗?或者也许某些方法用给定的旋转角度校正shadowOffset?手动校正90°的偏移很容易,所以这是没有选择;)

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

看起来应该是这样的:

谢谢提前预订!

在Bartosz Ciechanowski的帮助下,现在可行了!

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;

这导致:

而不是

推荐答案

假设 anAngle 以弧度为单位:

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

这篇关于如何绘制带有阴影的旋转UIView,但也不会旋转阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆