2012-04-23 6 views
5

私はこれを数日前から試みています。私はスプライトシートローダを作成していますが、逆方向のスプライトもロードできる必要があります。これは、すでにロードしたイメージを反転させることを伴います。UIImageを反転(ミラーリング)しようとしたところ、何が問題になったのですか?

私はすでにUIImageOrientation/UIImageOrientationUpMirroredメソッドを使用してこれを実行しようとしていますが、これはまったく効果がなく、以前とまったく同じ向きでフレームを描画します。

私はそれ以来、少し複雑な方法を試みましたが、これについては以下で説明します。しかし、アプリケーションにロードされるときとまったく同じ方法で画像を描画します。 (ミラーされていない)。

私の考えのパターンに従うことができるように、私のコメントと一緒に以下の方法を含めました。あなたは私が間違っていることを見ることができますか?

- (UIImage*) getFlippedFrame:(UIImage*) imageToFlip 
{ 
//create a context to draw that shizz into 
UIGraphicsBeginImageContext(imageToFlip.size); 
CGContextRef currentContext = UIGraphicsGetCurrentContext(); 



//WHERE YOU LEFT OFF. you're attempting to find a way to flip the image in imagetoflip. and return it as a new UIimage. But no luck so far. 
[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)]; 

//take the current context with the old frame drawn in and flip it. 
CGContextScaleCTM(currentContext, -1.0, 1.0); 

//create a UIImage made from the flipped context. However will the transformation survive the transition to UIImage? UPDATE: Apparently not. 

UIImage* flippedFrame = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return flippedFrame; 
} 

、 ガイ、ありがとうございました。

答えて

6

コンテキストの変換を変更してから描画する必要があると思います。また、あなたが負の座標にフリップされるため、変換する必要があるので、(コメントに基づいて編集した)

CGContextTranslateCTM(currentContext, imageToFlip.size.width, 0);  
CGContextScaleCTM(currentContext, -1.0, 1.0); 
[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)]; 

NOTEで

[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)]; 
CGContextScaleCTM(currentContext, -1.0, 1.0); 

に代わる:コメントから、

を使用するためのカテゴリ
@implementation UIImage (Flip) 
    - (UIImage*)horizontalFlip { 
    UIGraphicsBeginImageContext(self.size); 
    CGContextRef current_context = UIGraphicsGetCurrentContext();       
    CGContextTranslateCTM(current_context, self.size.width, 0); 
    CGContextScaleCTM(current_context, -1.0, 1.0); 
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; 
    UIImage *flipped_img = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return flipped_img; 
    } 
@end 
+0

私は以前これを試していましたが、私は混乱して、間違った方向(-imagetoflip.size.width)でコンテキストを翻訳したと思います。私はまた、THENの縮尺を翻訳しました。これは最終的に描かれたときにイメージを消した。あなたの提案は同じですが、私はそれがイメージを少なくとも変えるほど正しい軌道に乗っていると感じています。たぶん私が探しているものが見つかるまで、翻訳を微調整するだけの問題です。 –

+0

また、コアグラフィックスについて少し知っていれば、なぜ私たちがそれに描画するコンテキストを変換するのか教えていただけますか?私はあなたがコンテキストに描画してから、コンテキストを両方とも一緒に変換すると思っていたでしょうが、これは明らかに間違っています。 –

+0

ああ、ありがとうございます。 –

関連する問題