user5317212
user5317212

Reputation:

Android - Dynamic Mask Shape

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.

Upvotes: 1

Views: 1062

Answers (1)

dtx12
dtx12

Reputation: 4488

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;
    }
}

Upvotes: 2

Related Questions