Iphone 如何在UIButton中旋转imageView,而不是缩放它

Iphone 如何在UIButton中旋转imageView,而不是缩放它,iphone,cocoa-touch,uibutton,core-graphics,Iphone,Cocoa Touch,Uibutton,Core Graphics,我正在努力旋转UIBUtton的imageView属性,而不进行缩放。有问题的图像是24x18-比它的高宽-但一旦旋转到位,图像将被缩放以保持这些尺寸-给我留下一个非常压扁的图像。我怎样才能防止这种情况 下面是我的代码 -(IBAction)rotateButton { NSLog( @"Rotating button" ); [UIView beginAnimations:@"rotate" context:nil]; [UIView setAnimationDuration:.5f]; i

我正在努力旋转UIBUtton的imageView属性,而不进行缩放。有问题的图像是24x18-比它的高宽-但一旦旋转到位,图像将被缩放以保持这些尺寸-给我留下一个非常压扁的图像。我怎样才能防止这种情况

下面是我的代码

-(IBAction)rotateButton
{
NSLog( @"Rotating button" );

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:.5f];
if( CGAffineTransformEqualToTransform( button.imageView.transform, CGAffineTransformIdentity ) )
{
    button.imageView.transform = CGAffineTransformMakeRotation(M_PI/2);
} else {
    button.imageView.transform = CGAffineTransformIdentity;
}
[UIView commitAnimations];
}
如果我将转换应用于按钮而不是button.imageView,则不会发生这种情况,因此我猜这是imageView的一个属性,我没有设置正确

欢迎你的提示和嘘声


M.

我看到UIButtons的UIImageView属性的行为非常奇怪——它们的一些属性似乎是只读的,包括您在这里讨论的UIViewContentMode设置


我找到的最好的解决方案是用一个单独的UIImageView模拟“包含图像的按钮”设置,并在其上放置一个空的自定义样式的UIButton。为您管理图像提供了更大的灵活性。

在视图加载的某个位置初始化视图时应用以下代码。这会有帮助的。您在上面得到的答案不是真实答案:)


我发现子类化
ui按钮
layoutSubviews
过程中删除转换是有效的,如下所示:

class RotatableImageButton: UIButton {
    override func layoutSubviews() {
        let originalTransform = imageView?.transform
        imageView?.transform = CGAffineTransformIdentity
        super.layoutSubviews()
        if let originalTransform = originalTransform {
            imageView?.transform = originalTransform
        }
    }
}

我对普通UIImageView也有类似的问题,当你旋转(不是应该发生的事情)时,内容会变得疯狂,这是通过将contentMode设置为“中心”来修复的——感谢你的这一见解!FWIW,即使将变换应用于按钮,我也会得到压扁的结果。而且它不会发生在模拟器上,只会发生在设备上。值得注意的是,您不能设置(或依赖)按钮。imageEdgeInsets因为
clipsToBounds=NO
没有效果。这解决了我的一个问题,即通过
self.btnSettings.imageView!旋转90°时,圆形系统图标“gear”变成椭圆形!。transform=self.btnSettings.imageView!。变换。旋转(按:CGFloat(.pi/2.0))
且仅正确显示为0°和180°的圆。使用类后,齿轮图标在旋转90°增量时正确保持其形状。谢谢
class RotatableImageButton: UIButton {
    override func layoutSubviews() {
        let originalTransform = imageView?.transform
        imageView?.transform = CGAffineTransformIdentity
        super.layoutSubviews()
        if let originalTransform = originalTransform {
            imageView?.transform = originalTransform
        }
    }
}