Android - 繪製可拖曳圖片

摘要:Android - 繪製可拖曳圖片

這是按照書中範例,造著練習,做筆記

package com.tomlai.draw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import com.tomlai.demo.app.R;

public class MyView extends View{
    private Context context;
    private Bitmap mBitmap;
    private Paint mPaint;
    private int iWidth;
    private int iHeight;
    private float imageX = -1.0f;
    private float imageY = -1.0f;
    private float deltaX = 0f;
    private float deltaY = 0f ;
    private boolean bImageTouched = false;    
    
    public MyView(Context context) {
        super(context);
        this.context = context;
        mPaint = new Paint();
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        iWidth = w;
        iHeight = h;        
        imageX = w*2/3;
        imageY = h*2/3;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //畫背景
        canvas.drawColor(Color.WHITE);
        
        //畫圖片
        canvas.drawBitmap(mBitmap, imageX-mBitmap.getWidth()/2, imageY-mBitmap.getHeight()/2,null);
    }    

    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        
        int action = event.getAction();
        
        if(action==MotionEvent.ACTION_DOWN) {
            if(x>= imageX && x<=imageX + mBitmap.getWidth() && y>= imageY && y <=imageY + mBitmap.getHeight()) {
                deltaX = x - imageX;
                deltaY = y - imageY;
                bImageTouched = true;
            }
        } else if (action==MotionEvent.ACTION_MOVE) {
            if(bImageTouched) {
                imageX = x - deltaX;
                imageY = y - deltaY;
            }
        } else if (action==MotionEvent.ACTION_UP) {
            if(bImageTouched) {
                bImageTouched = false;
            }
        }        
        
        //重繪
        invalidate();
        return true;
    }    
}

在Activity要撰寫如下

import android.app.Activity;
import android.os.Bundle;

public class DrawActivity extends Activity {
    public MyView mMyView;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMyView = new MyView(this);
        setContentView(mMyView);
    }
}