开发者

In my Android app,how do I move the images from their position?

I have a class Panel which overrides onDraw() method as below.I have two images mentioned in canvas.drawBitmap(),as of now their position is fixed. Is it possible for me to move these two images from bottom to top on my emulator? Code is:

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

    @Override
    public void onDraw(Canvas canvas) {
        Bitmap image1 = BitmapFactory.decodeResource(getResources(), R.drawable.btnpre);
        ca开发者_C百科nvas.drawColor(Color.CYAN);
        canvas.drawBitmap(Image1, 10, 10, null);
        Bitmap Image2 = BitmapFactory.decodeResource(getResources(), R.drawable.btnpre);
        canvas.drawBitmap(Image2, 100, 100, null);

    }
 }


Re-write your code like this canvas.drawBitmap(Image1, x, y, null);.

And write a thread to change the value of x or y over time.

Once you change the value of x or y, please call invalidate in your Panel.java to redraw the view.


use variables in onDraw call for values of x,y where you want to draw. I modified your code to redraw itself to new coordinates after 10 seconds of first draw call. It will give you an idea to use variables inside draw call to dynamically change where you draw. Hope I have answered your question

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

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            x1 = 20;
            y1 = 20;

            x2 = 120;
            y2 = 120;
            invalidate();
        }
    }
    private int x1 = 10;
    private int y1 = 10;

    private int x2 = 100;
    private int y2 = 100;
    private boolean drawAfterTenSecs = false;


    @Override
    public void onDraw(Canvas canvas) {
        Bitmap image1 = BitmapFactory.decodeResource(getResources(), R.drawable.btnpre);
        canvas.drawColor(Color.CYAN);
        canvas.drawBitmap(Image1, x1, y1, null);
        Bitmap Image2 = BitmapFactory.decodeResource(getResources(), R.drawable.btnpre);
        canvas.drawBitmap(Image2, x2, y2, null);
        if(!drawAfterTenSecs) {
            handler.sendEmptyMessageDelayed (-1, 10000)
            drawAfterTenSecs = true;
        }
    }

 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜