【问题标题】:Flipping Drawable on an X or Y axis在 X 或 Y 轴上翻转 Drawable
【发布时间】:2010-12-29 23:54:54
【问题描述】:

似乎是一个愚蠢的问题,但我看不到任何使用Drawable 类中的方法的方法。然后我想也许我必须以某种方式翻转 Canvas.. 仍然找不到合适的方法。

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

【问题讨论】:

    标签: java android drawable


    【解决方案1】:

    从 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
    • 你为什么要扩展Activity?我无法想象你会希望整个内容视图是 Bitmap 被翻转的情况
    • “这可能有点矫枉过正,但这里有一个小示例应用程序”。这是一个完全独立的示例,留作练习,以对您的使用有意义的方式实现它。