在X或Y轴上翻转Drawable

4

这似乎是一个愚蠢的问题,但是我无法找到使用Drawable类中的方法来完成这个操作的任何方法。然后我想也许我需要以某种方式翻转画布.. 仍然找不到合适的方法。

我只需要在y轴上“翻转”一个Drawable.. 最好是在中心y轴。我该怎么做?

1个回答

8

从一个10k英尺的高度来看,您想创建一个新的位图并指定一个变换矩阵来翻转该位图。

这可能有点过度,但这里有一个小示例应用程序,说明如何做到这一点。如所写的那样,变换矩阵的预缩放(-1.0f,1.0f)将图像在x方向上翻转,预缩放(1.0f,-1.0f)将其在y方向上翻转。

public class flip extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Set view to our created view
        setContentView(new drawView(this));
    }

    private class drawView extends View{
        public drawView(Context context){
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            //Load the jellyfish drawable
            Bitmap sprite = BitmapFactory.decodeResource(this.getResources(), R.drawable.jellyfish);

            //Create a matrix to be used to transform the bitmap
            Matrix mirrorMatrix = new Matrix();

            //Set the matrix to mirror the image in the x direction
            mirrorMatrix.preScale(-1.0f, 1.0f);

            //Create a flipped sprite using the transform matrix and the original sprite
            Bitmap fSprite = Bitmap.createBitmap(sprite, 0, 0, sprite.getWidth(), sprite.getHeight(), mirrorMatrix, false);

            //Draw the first sprite
            canvas.drawBitmap(sprite, 0, 0, null);

            //Draw the second sprite 5 pixels to the right of the 1st sprite
            canvas.drawBitmap(fSprite, sprite.getWidth() + 5, 0, null);
        }
    }
}

谢谢!我还不太了解如何使用矩阵。也许这可以帮助我理解它 :p - Snailer
为什么要扩展“Activity”?我无法想象在哪种情况下您希望整个内容视图成为被翻转的“Bitmap”。 - Dylan Vander Berg
这可能有点过头了,但这是一个小的示例应用程序。它是完全自包含的示例,留给您实现以符合您的使用方式。 - Error 454

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接