iOS:如何根据当前方向翻转图像



我正在尝试检查图像的当前方向,并将其翻转到与当前方向相反的方向。

如果我的屏幕上只有一个元素,这个代码就可以工作,但只要我增加数组,就有50/50的机会获得正确的方向。

-(IBAction)flipBtn:(id)sender
{
    UIImage* flippedImage;
    if(flipBtn.tag==FLIP_BUTTON_TAG)
    {
        UIImage* sourceImage1 = self.outletImageView.image;
        flippedImage = [UIImage imageWithCGImage:sourceImage1.CGImage scale:1.0 orientation: UIImageOrientationUpMirrored];
        flipBtn.tag = FLIP_VUTTON_TAG2;
    }else{
        UIImage* sourceImage1 = self.outletImageView.image;
        flippedImage = [UIImage imageWithCGImage:sourceImage1.CGImage scale:1.0 orientation: UIImageOrientationUp];
        flipBtn.tag = FLIP_BUTTON_TAG;
    }
     NSInteger index1 = [imgViewArray indexOfObject:self.outletImageView];
    [imgViewArray removeObject:self.outletImageView];
    self.outletImageView.image = flippedImage;
    [imgViewArray insertObject:self.outletImageView atIndex:index1];
}

代替[imgViewArray removeObject:self.outletImageView];

写入:[imgViewArray removeObjectAtIndex:index1];

然后,您需要检查flippedImage.imageOrientation == UIImageOrientationUp,看看它是否反转,并进行适当的更改。

您可以通过访问信息字典[info objectForKey:@"Orientation"] 来验证图片的方向

这里有一个方法,它将根据您之前的检查返回新的所需方向(您将通过flippedImage.imageOrientation作为参数):

- (UIImageOrientation)orientation:(int)orientation
{
    UIImageOrientation newOrientation;
    switch (orientation)
    {
        case 1:
            newOrientation = UIImageOrientationUp;
            break;
        case 2:
            newOrientation = UIImageOrientationUpMirrored;
            break;
    }  
    return newOrientation;  
}