Vahan
Vahan

Reputation: 3268

How to change the color of a touched region in ImageView?

I need to set white color to the region that the user touches on an ImageView. If I setOnTouchListener to the ImageView and get the x and y positions of the touch, how can I change the appropriate pixel values in the ImageView? or is there a better solution?

Upvotes: 1

Views: 1309

Answers (1)

sberezin
sberezin

Reputation: 3296

I think the easiest solution is to extend ImageView.

Here is a brief example that draws a black circle around touched area:

class TouchableImageView extends ImageView {
    private float x, y;
    private Paint paint;

    public TouchableImageView(Context context) {
        super(context);
        init();
    }

    public TouchableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TouchableImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TouchableImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    void init() {
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
      if (event.getAction() == MotionEvent.ACTION_DOWN) {
        x = event.getX();
        y = event.getY();
        invalidate();
      }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //Just for example - draw a circle around touch area:
        if(x!=0 || y!=0)
        canvas.drawCircle(x, y, 25, paint);
    }
}

Edit :

If you want to save the result as a bitmap - you need several more steps as described here and here.

In short you should follow these steps :

  1. Create a new Bitmap of the required size
  2. Create new canvas for the created Bitmap - new Canvas(bitmap)
  3. Re-draw all you need upon this canvas
  4. Save bitmap as a graphics file

Upvotes: 2

Related Questions