1

I am trying to implement Masking of an image for my android project. I am trying to accomplish the same as below image :

enter image description here

and the output would be the same as below link:

enter image description here

The link below is close to what I want to achieve only that I need to create the mask at runtime and handle onTouchListener to draw the mask but how?

Masking(crop) image in frame

I can't figure out myself and I feel stuck at this problem. Any help or tutorials that will help is highly appreciated.

Community
  • 1
  • 1

1 Answers1

2

Although I didn't write a complete solution it could show you right direction.

package com.example.masktest.app;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MaskDrawingView extends View {

    private Path path = new Path();
    private Paint pathPaint = new Paint();

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

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

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

    private void init() {
        pathPaint.setStyle(Paint.Style.STROKE);
        pathPaint.setAlpha(150);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(path, pathPaint);
        invalidate();
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.lineTo(event.getX(), event.getY());
                break;
        }
        return super.onTouchEvent(event);
    }

    public Bitmap finishDrawingAndGetMask() {
        pathPaint.setStyle(Paint.Style.FILL);
        path.close();
        setDrawingCacheEnabled(true);
        Bitmap result = Bitmap.createBitmap(getDrawingCache());
        setDrawingCacheEnabled(false);
        path.reset();
        return result;
    }
}
dtx12
  • 4,438
  • 1
  • 16
  • 12
  • Thanks for your response but I need the view to be adjusted when the user touches the edge same as the first image. –  Sep 10 '15 at 09:38
  • In my class you may basicly create a mask using touches for your image. Then you just need to apply this mask to your image, if you need something other, you'd better provide a video example. – dtx12 Sep 10 '15 at 15:28