如何在UIButton中旋转图像视图,而不是缩放它

问题描述:

我正在努力旋转UIButton的imageView属性而不缩放它。有问题的图像是24x18 - 比高 - 宽,但一旦旋转到位图像缩放,以保持这些尺寸 - 留给我一个非常挤压的图像。我怎样才能防止这一点?如何在UIButton中旋转图像视图,而不是缩放它

下面是我的代码..

-(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.

+0

FWIW,我得到的压扁即使将变换应用于按钮也会导致结果。它不会发生在模拟器上,只发生在设备上。 – rounak 2014-09-16 15:25:50

我见过UIButtons的UIImageView的财产表现得非常奇怪 - 这似乎是他们的一些属性是只读的,包括UIViewContentMode设置这就是你在这里谈论的。

我发现的最好的解决方案是模仿包含一个单独的UIImageView的“包含图像的按钮”设置和坐在它上面的空的定制样式的UIButton。为您提供更多灵活性来管理图像。

+1

我有一个普通的UIImageViews类似的问题,当你旋转(不会发生什么),通过设置contentMode到“中心”修复时会疯狂的内容 - 谢谢你的洞察力! – Adam 2011-05-05 23:25:08

应用以下代码初始化视图中某处的视图时加载。这将有所帮助。您在上面得到的答案是不是一个真正的答案:)

button.imageView.clipsToBounds = NO; 
button.imageView.contentMode = UIViewContentModeCenter; 
+2

这解决了我的问题! – 2013-03-19 16:17:02

+0

这工作完美! – 2013-05-07 14:08:16

+1

感谢@Nikita这对我有用! – Desmond 2013-12-06 02:19:50

我发现,子类UIButton删除的变换过程中layoutSubviews工作,像这样:

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

适合我! – Mete 2017-05-09 15:06:24