Search code examples
androidimageviewdivideregions

android divide image into sub images ,recognizing


I want to divide the image into sub images and when I click on a part of the image will give me the name of the region, for example, this is my question how to recognize a region from the image, or how to divide the image into sub-images and use it in imageViews

And thank you in advance


Solution

  • In my opinion @fractalwrench's idea is quite good for your case. Basic steps are listed below.

    • Subclass Android ImageView. For example, MultiRegionImageView.
    • Override its onTouchEvent method. (This method gets called whenever user touches the view)
    • User touches the image and thereby onTouchEvent is called and provides the exact touch point (x, y).

    • Declare another method or interface which determines at which region a given point is. For example, getRegionByPoint(int x, int y)

    • If you would like to highlight that region boundaries, you could use paths. First off, you should define paths and save them into a raw file (XML, for example), then using region ID, fetch its path and finally draw that path over the main image.

    • For drawing a path over the main image, you should also override onDraw method of ImageView class and use canvas.drawPath();


    public class MultiRegionImageView extends ImageView {
        RegionProvider mRegionProvider;
        int mId = -1;
        private Paint mPaint;
    
        public MultiRegionImageView(Context context) {
            super(context);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            mId = mRegionProvider.getRegionIdByPoint(event.getX(), event.getY());
            return super.onTouchEvent(event);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if(mId != -1) {
                canvas.drawPath(mRegionProvider.getRegionBoundaryPath(mId), mPaint);
            }
        }
    
        public interface RegionProvider{
            int getRegionIdByPoint(float x, float y);
            Path getRegionBoundaryPath(int id);
        }
    }