Mar 19, 2012

Touch to move Bitmap inside a custom View

Refer to the article Detect Touch Event, test on Custom View. Modify to add a Bitmap in the custom view, if user touch the View over the bitmap, it will be moved accordingly.

Touch to move Bitmap inside a custom View
package com.TestSingleTouch;

import android.app.Activity;
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.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class TestSingleTouch extends Activity {


public class TouchView extends View {

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float x, y;
boolean touching = false;

Bitmap bm = BitmapFactory.decodeResource(
getResources(),
R.drawable.ic_launcher);
int bm_x = 0;
int bm_y = 0;
int bm_w = bm.getWidth();
int bm_h = bm.getHeight();
int bm_offsetx;
int bm_offsety;
boolean dm_touched = false;


public TouchView(Context context) {

super(context);
// TODO Auto-generated constructor stub

}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);

if(touching){
canvas.drawRect(x, y, x+bm_w, y+bm_h, paint);
}

canvas.drawBitmap(bm, bm_x, bm_y, paint);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

@Override

public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_MOVE:
x = event.getX();
y = event.getY();
touching = true;

if(dm_touched){
bm_x = (int)x - bm_offsetx;
bm_y = (int)y - bm_offsety;
}

break;
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
touching = true;

//check if bm touched
if((x > bm_x)
&& (x < bm_x+bm_w)
&& (y > bm_y)
&& (y < bm_y+bm_h)){
bm_offsetx = (int)x - bm_x;
bm_offsety = (int)y - bm_y;
dm_touched = true;
}

break;
case MotionEvent.ACTION_UP:
default:
dm_touched = false;
touching = false;
}

invalidate();
return true;
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchView(this));

}
}

No comments:

Post a Comment

Infolinks In Text Ads