Adding Touch Listener to ImageView : ImageView « UI « Android






Adding Touch Listener to ImageView

  

package app.test;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class Test extends Activity implements OnTouchListener {
  ImageView imageView;
  Bitmap bitmap;
  Canvas canvas;
  Paint paint;

  float downx = 0,downy = 0,upx = 0,upy = 0;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imageView = (ImageView) this.findViewById(R.id.ImageView);
    Display currentDisplay = getWindowManager().getDefaultDisplay();
    float dw = currentDisplay.getWidth();
    float dh = currentDisplay.getHeight();

    bitmap = Bitmap.createBitmap((int) dw, (int) dh,
        Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bitmap);
    paint = new Paint();
    paint.setColor(Color.GREEN);
    imageView.setImageBitmap(bitmap);
    imageView.setOnTouchListener(this);
  }

  public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
      downx = event.getX();
      downy = event.getY();
      break;
    case MotionEvent.ACTION_MOVE:
      upx = event.getX();
      upy = event.getY();
      canvas.drawLine(downx, downy, upx, upy, paint);
      imageView.invalidate();
      downx = upx;
      downy = upy;
      break;
    case MotionEvent.ACTION_UP:
      upx = event.getX();
      upy = event.getY();
      canvas.drawLine(downx, downy, upx, upy, paint);
      imageView.invalidate();
      break;
    case MotionEvent.ACTION_CANCEL:
      break;
    default:
      break;
    }
    return true;
  }
}

   
    
  








Related examples in the same category

1.Set ImageView width, height
2.extends ImageView
3.Load image with ImageView
4.Using ImageView within ListActivity
5.Using ImageView to display image and reference Image resource in layout xml file
6.ImageView background
7.Set Layout Parameters, Scale Type, background for ImageView
8.Using ImageView to display Image
9.ImageView click listener
10.Set Image resource for ImageView
11.Set Image Bitmap for ImageView
12.Set image Uri for ImageView
13.Demonstrates setting size constraints on android.widget.ImageView
14.Create ImageView
15.Create an image view, given a drawable. you can set the max size of this imageview as well.
16.download images from the Internet and binds those with the provided ImageView.
17.Choose a Picture