I'm using CameraX to scan QR. For the UI side, I need to create a translucent black background along with a transparent box in the center (of given side [or of given padding if the side can be calculated]).
I tried using different solutions on stackoverflow but for some reason was unable to achieve this. Currently, I'm trying to use this solution to create a square of given side (width/height) but am unable to do so. I tried modifying the code provided in the first answer here How to create a 'transparent circle inside rectangle' shape in XML in Android?, but it isn't working as expected.
Code:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class QROverlay extends View {
private Paint mTransparentPaint;
private Paint mSemiBlackPaint;
private RectF rectF;
private Path mPath = new Path();
private int cx = 0;
private int cy = 0;
private final int SIDE = 10;
public QROverlay(Context context) {
super(context);
initPaints();
}
public QROverlay(Context context, AttributeSet attrs) {
super(context, attrs);
initPaints();
}
public QROverlay(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaints();
}
private void initPaints() {
mTransparentPaint = new Paint();
mTransparentPaint.setColor(Color.TRANSPARENT);
mTransparentPaint.setStrokeWidth(10);
mSemiBlackPaint = new Paint();
mSemiBlackPaint.setColor(Color.parseColor("#A6000000"));
mSemiBlackPaint.setStrokeWidth(10);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPath.reset();
RectF rectF = new RectF(
getLeft() + 100, getTop() + 100, getRight() - 100, getBottom() - 100
);
// mPath.addCircle(canvas.getWidth() / 3, canvas.getHeight() / 3, 0, Path.Direction);
mPath.addRect(rectF, Path.Direction.CW);
mPath.setFillType(Path.FillType.INVERSE_EVEN_ODD);
canvas.drawRect(rectF, mTransparentPaint);
canvas.drawPath(mPath, mSemiBlackPaint);
canvas.clipPath(mPath);
canvas.drawColor(Color.parseColor("#A6000000"));
}
}
Could someone please help me out with this code?