Search code examples
androidandroid-fragmentscanvasimageviewontouch

Efficiently Drawing over an imageView that resides inside of a fragment in response to a touch event


I have an application in which I display an image in an ImageView that resides in a fragment seen from the activity. I would like to respond to touch events on the ImageView by drawing small dot-like circles centered around the coordinates of the touch event.

After some googling and reading I implemented the following code inside the fragment class:

public class ImageViewFragment extends Fragment implements View.OnTouchListener
{ 
  private ImageView mImageView;
  private Bitmap mBitmap;
  private List<Pair<Integer, Integer>> mScribblePointsCoords;
  private Paint mPaint;

public interface OnScribbleUpdate
{
    void onNewScribblePoint(List<Pair<Integer, Integer>> coordinates);

}

@Override
public boolean onTouch(View v, MotionEvent event)
{
    v.onTouchEvent(event);
    return true;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    mScribblePointsCoords = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.image_view_fragment, container, false);
    view.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if(event.getAction() == MotionEvent.ACTION_DOWN)
            {
                int x = (int) event.getX();
                int y = (int) event.getY();
                mScribblePointsCoords.add(new Pair<>(x, y));
                Bitmap tempBitmap = mBitmap.copy(mBitmap.getConfig(), true);
                Canvas canvas = new Canvas(tempBitmap);
                canvas.drawCircle(x, y, R.dimen.default_scribble_point_radius, mPaint);
                mImageView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));
                mBitmap = tempBitmap;
                return true;
            }
            return false;
        }
    });
    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mImageView = view.findViewById(R.id.new_photo_view);
    mImageView.setImageBitmap(mBitmap);
    return view;
}

@Override
public void onResume()
{
    super.onResume();
    mImageView.setImageBitmap(mBitmap);
}

public void setImage(Bitmap bmp)
{
    mBitmap = bmp.copy(bmp.getConfig(), false);
    if(this.isResumed())
    {
        mImageView.setImageBitmap(mBitmap);
    }
}

public void clearScribble()
{
    mScribblePointsCoords.clear();
}

public List<Pair<Integer, Integer>> getScribbleCoordinates()
{
    return mScribblePointsCoords;
}
}

Edit: image_view_fragment.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="cofproject.tau.android.cof.ImageViewFragment">

    <ImageView
        android:id="@+id/new_photo_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        app:srcCompat="@android:color/background_dark"/>
</FrameLayout>

End of Edit

Now, the problem with this is that I get the entirety of the ImageView colored a solid blue (I tried different radius sizes for R.dimen.default_scribble_point_radius such as 5, 0.5 and 0.1 but to no avail).

Before:

Before clicking the image

After:

After clicking the image

I have a three part question:

  1. What am I doing wrong and how can I get a simple dot-like circle instead of having the entire ImageView going blue.

  2. I think my onTouch(View v, MotionEvent event) method is very inefficient as it would have to redraw the bitmap for each dot added and I was wondering if there is an efficient way to acheive the same thing.

  3. Would using a transperent view of somesort on which the drawing will take place save me trouble, and if so how can such a thing be achieved?

Your opinion and guidance is greatly appreciated.


Solution

  • You should go with a transparent View which is positioned exactly above (z-wise) the ImageView. The main reason for this is performance: an ImageView is a rather heavy type of View when it comes to drawing small blue circles.

    So you create a custom View which will do the drawing and place it on top of the ImageView. I achieved this by putting them both in a FrameLayout:

    <FrameLayout
        android:layout_width="200dp"
        android:layout_height="200dp">
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
        <com.example.paintingcircles.DottedView
            android:id="@+id/dottedView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </FrameLayout>
    

    I followed your setup and used an anonymous OnTouchListener but of course you could just as well have DottedView override onTouchEvent().

    In onCreate():

    final DottedView dottedView = (DottedView) findViewById(R.id.dottedView);
    dottedView.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View view, MotionEvent event)
        {
            if(event.getAction() == MotionEvent.ACTION_DOWN)
            {
                int x = (int) event.getX();
                int y = (int) event.getY();
                dottedView.addScribblePointsCoords(new Pair<>(x, y));
                dottedView.invalidate();
                return true;
            }
            return false;
        }
    });
    

    DottedView.java:

    public class DottedView extends View
    {
        private ArrayList<Pair<Integer, Integer>> mScribblePointsCoords = new ArrayList<>();
        private int radius = 5;
        private Paint mPaint;
    
        public DottedView(Context context)
        {
            super(context);
            init();
        }
    
        public DottedView(Context context, @Nullable AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
    
        public DottedView(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
        {
            super(context, attrs, defStyleAttr);
            init();
        }
    
        @Override
        protected void onDraw(Canvas canvas)
        {
            super.onDraw(canvas);
            for (Pair<Integer, Integer> pair: mScribblePointsCoords){
                canvas.drawCircle(pair.first, pair.second, radius, mPaint);
            }
        }
    
        public void addScribblePointsCoords(Pair pair){
            mScribblePointsCoords.add(pair);
        }
    
        private void init()
        {
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setColor(Color.BLUE);
        }
    }