开发者

Flipping Drawable on an X or Y axis

开发者 https://www.devze.com 2023-02-01 12:17 出处:网络
This seems like a dumb question, but I couldn\'t see any way to do this using methods in the Drawable class. Then I thought maybe I\'d have to flip the Canvas开发者_运维知识库 in some way.. still coul

This seems like a dumb question, but I couldn't see any way to do this using methods in the Drawable class. Then I thought maybe I'd have to flip the Canvas开发者_运维知识库 in some way.. still couldn't find a suitable method.

I just need to "flip" a Drawable on it's y-axis.. the center y preferably. How can I do this?


From a 10k ft level, you want to create a new bitmap and specify a transform matrix to flip the bitmap.

This may be a bit overkill, but here is a small sample application that illustrates how to do this. As written, the transform matrix prescale of (-1.0f, 1.0f) flips the image in the x direction, a prescale of (1.0f, -1.0f) would flip it in the y direction.

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);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号