从右到左语言翻转UIImageViews

当使用像阿拉伯语这样的RTL语言时,iOS自动翻转整个ViewController ,并且在大部分的布局,特别是文本方面做得很好。 默认行为是翻转布局,但离开UIImageViews相同的方向(因为你通常不想扭转图像)。

当手机设置为RTL语言时,是否可以指定某些图像应该翻转(如箭头)?

iOS 9包含可以使用的imageFlippedForRightToLeftLayoutDirection方法,该方法在RTL本地化时自动翻转UIImageView中的图像。

当手机设置为RTL语言时,必须手动翻转所需的UIImageView中的UIImage。 这个代码很容易实现:

 UIImage* defaultImage = [UIImage imageNamed:@"default.png"]; UIImage* flipImage = [UIImage imageWithCGImage:sourceImage.CGImage scale:1.0 orientation: UIImageOrientationUpMirrored]; myImageview.image = flipImage; 

我结束了使用本地化的图像的前进和后退箭头。 这样做的好处是无需在图像的每个位置都添加代码,并且如果存在无法正常翻转的渐变,则可以清除箭头。

虽然我们等待iOS 9改进了从右到左的支持,但是您可以创build一个UIImageView子类并覆盖setImage以在镜像内镜像@ nikos -mbuild议并调用super.image = flipImage

这样,您可以轻松地使用Interface Builder中的自定义类来设置所有想要翻转的图像视图,而无需添加IBOutlet

如果当前语言是RTL(从右到左),我们可以使用imageFlippedForRightToLeftLayoutDirection返回翻转的图像。 即

Objective-C的

 UIImage * flippedImage = [[UIImage imageNamed:@"imageName"] imageFlippedForRightToLeftLayoutDirection]; 

Swift 3

 let flippedImage = UIImage(named: "imageName")?.imageFlippedForRightToLeftLayoutDirection() 

来源: Apple Docs