6

I am beginner in Android and I have a rather simple question. I have created a custom view and then injected it into another layout through xml. I want to make the background of this custom view transparent.

xml injection of my custom view:

<com.sagar.utils.ConnectDotsView
                android:id="@+id/connect_dots_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

Here is the code of the custom View:

public class ConnectDotsView extends View {

    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mPaint;
    private static final int TOUCH_TOLERANCE_DP = 24;
    private static final int BACKGROUND = 0xFFDDDDDD;
    // Points to be connected.
    private List<Point> mPoints = new ArrayList<>();
    private int mLastPointIndex = 0;
    private int mTouchTolerance;
    private boolean isPathStarted = false;
    CompleteListener completeListener;

    public ConnectDotsView(Context context) {
        super(context);
        mCanvas = new Canvas();
        mPath = new Path();
        initPaint();
    }



    public interface CompleteListener {
        void onCompleteListener();
    }

    public void setOnCompleteListener(CompleteListener listener) {
        completeListener = listener;
    }

    public ConnectDotsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCanvas = new Canvas();
        mPath = new Path();
        initPaint();
    }

    public ConnectDotsView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mCanvas = new Canvas();
        mPath = new Path();
        initPaint();
    }

    public void clear() {
        mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mBitmap.eraseColor(BACKGROUND);
        mCanvas.setBitmap(mBitmap);
        invalidate();
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);
        clear();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(BACKGROUND);
        canvas.drawBitmap(mBitmap, 0, 0, null);
        canvas.drawPath(mPath, mPaint);

        mPaint.setColor(Color.parseColor("#56CBF9"));
        // TODO remove if you don't want points to be visible.
        for (Point point : mPoints) {
            canvas.drawPoint(point.x, point.y, mPaint);
            mPaint.setColor(Color.BLACK);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up(x, y);
                invalidate();
                break;
        }
        return true;
    }

    private void touch_start(float x, float y) {

        if (checkPoint(x, y, mLastPointIndex)) {
            mPath.reset();
            // User starts from given point so path can be drawn.
            isPathStarted = true;
        } else {
            // User starts move from point which does not belong to mPoints list
            isPathStarted = false;
        }

    }

    private void touch_move(float x, float y) {
        if (isPathStarted) {
            mPath.reset();
            Point point = mPoints.get(mLastPointIndex);
            mPath.moveTo(point.x, point.y);
            if (checkPoint(x, y, mLastPointIndex + 1)) {
                point = mPoints.get(mLastPointIndex + 1);
                mPath.lineTo(point.x, point.y);
                mCanvas.drawPath(mPath, mPaint);
                mPath.reset();
                ++mLastPointIndex;
            } else {
                int positionIndex = mLastPointIndex + 1;
                if (positionIndex >= mPoints.size()) {
                    completeListener.onCompleteListener();
                } else {
                    mPath.lineTo(x, y);
                }
            }
        }
    }

    private void touch_up(float x, float y) {
        mPath.reset();
        if (checkPoint(x, y, mLastPointIndex + 1) && isPathStarted) {
            // Move finished at valid point so I draw whole line.
            // That's the start point of current line segment.
            Point point = mPoints.get(mLastPointIndex);
            mPath.moveTo(point.x, point.y);
            // And that's the end point.
            point = mPoints.get(mLastPointIndex + 1);
            mPath.lineTo(point.x, point.y);
            mCanvas.drawPath(mPath, mPaint);
            mPath.reset();
            // Increment point index.
            ++mLastPointIndex;
            isPathStarted = false;
        }

    }

    /**
     * Checks if user touch point with some tolerance
     */
    private boolean checkPoint(float x, float y, int pointIndex) {
        if (pointIndex >= mPoints.size()) {
            // All dots already connected.
            return false;
        }
        Point point = mPoints.get(pointIndex);
        if (x > (point.x - mTouchTolerance) && x < (point.x + mTouchTolerance)) {
            if (y > (point.y - mTouchTolerance) && y < (point.y + mTouchTolerance)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Sets up paint attributes.
     */
    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);
        mTouchTolerance = dp2px(TOUCH_TOLERANCE_DP);
    }

    /**
     * Converts dpi units to px
     *
     * @param dp
     * @return
     */
    private int dp2px(int dp) {
        Resources r = getContext().getResources();
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
        return (int) px;
    }

    public void setPaint(Paint paint) {
        this.mPaint = paint;
    }

    public Bitmap getBitmap() {
        return mBitmap;
    }

    public List<Point> getPoints() {
        return mPoints;
    }

    public void setPoints(List<Point> points) {
        mLastPointIndex = 0;
        this.mPoints = points;
    }
}

I want to make the above custom View's background as transparent. How can I achieve that either through xml or code?

Thanks in advance.

sagar suri
  • 4,351
  • 12
  • 59
  • 122

4 Answers4

4

In your Class ConnectDotsView change:

private static final int BACKGROUND = 0xFFDDDDDD;

to

private static final int BACKGROUND = Color.TRANSPARENT;

or

private static final int BACKGROUND = Color.parseColor("#00000000");

#00AABBCC = ARGB (00 is Alpha, AA is red, BB is green and CC is blue), 00 alpha is 0% and FF is 100%. This mean #00AABBCC will be transparent, #80AABBCC will be at 50% transparent and #FFAABBCC not transparent

Milos Lulic
  • 627
  • 5
  • 22
2

Change alpha of your parent view using view.setAlpha(float opacity) where 0f is fully transparent view.

Anton Kazakov
  • 2,740
  • 3
  • 23
  • 34
1

In your initPaint() method, call the following function:

    setBackgroundColor(R.color.colorTransparent);

And in the values/colors.xml folder, set your colorTransparent with RGBA as 00:

<color name="colorTransparent">#00000000</color>

Alternatively, when you call your custom view in xml, use: android:background="#00000000".

This should solve your problem.

Edited:

just use setBackgroundColor(Color.TRANSPARENT);

Or setBackgroundColor(0x00000000);

50% opacity: setBackgroundColor(0x80000000);

Anas Altair
  • 170
  • 2
  • 9
Robillo
  • 192
  • 11
  • How to control the transparency ? – sagar suri Sep 30 '17 at 08:39
  • You can control the transparency through xml: go to the preview mode of the xml of the activity in which you have declared your view, then open the properties tab, and click on the three dots alongside of the "background" attribute in properties tab. then on the dialog that pops up, at the top right, click on "add new resource" and then "color resource". you can now select a colour of your choice and the alpha (transparency) at the bottom. – Robillo Sep 30 '17 at 08:43
1

To control the extent of transparency, use @Robillo's code, but modify this:

<color name="colorTransparent">#xy000000</color>

replace xy with your desired opacity. 00 will be 0% opaque, FF is 100% opaque (ie white colour)

AD S2dios
  • 31
  • 5