Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set stroke color to draw a rectangle on canvas?

I want to draw a round rectangle which its stroke is blue and its fill is red, but I can't find a method in Paint class to set stroke color. How can I do that?

    mCanvas.drawColor(mBackgroundColor, PorterDuff.Mode.CLEAR);
    mCanvas.setDrawFilter(mPaintFlagsDrawFilter);

    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    mPaint.setColor(Color.RED);
    mPaint.setStrokeWidth(2);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mRectF.set(0, 0, mWidth, mHeight);
    mCanvas.drawRoundRect(mRectF, 10, 10, mPaint);
like image 416
sunjinbo Avatar asked Sep 13 '16 12:09

sunjinbo


People also ask

How do you fill color in Canva rectangle?

The fillRect() method is used to fill the rectangle using the given color. The default color of the fillRect() method is black. Parameters: This method accepts four parameters as mentioned above and described below: x: It stores the x-coordinate of top-left corner of rectangle.

How do you change stroke color in canvas?

To set the color of an HTML5 Canvas line, we can use the strokeStyle property of the canvas context, which can be set to a color string such as red, green, or blue, a hex value such as #FF0000 or #555, or an RGB value such as rgb(255, 0, 0).

What is rectangle stroke?

strokeRect() method of the Canvas 2D API draws a rectangle that is stroked (outlined) according to the current strokeStyle and other context settings. This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it.

How do you add a rectangle to a canvas?

To draw the rectangle onto a canvas, you can use the fill() or stroke() methods. Note: To both create and render a rectangle in one step, use the fillRect() or strokeRect() methods.


1 Answers

Paint only allows for one color at a time.

mCanvas.drawColor(mBackgroundColor, PorterDuff.Mode.CLEAR);
mCanvas.setDrawFilter(mPaintFlagsDrawFilter);

mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setColor(Color.RED);
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setColor(Color.BLUE);
mStrokePaint.setStrokeWidth(2);
mStrokePaint.setStrokeCap(Paint.Cap.ROUND);
mRectF.set(0, 0, mWidth, mHeight);
mCanvas.drawRoundRect(mRectF, 10, 10, mFillPaint);
mCanvas.drawRoundRect(mRectF, 10, 10, mStrokePaint);

If you find your rounded rectangle doesn't look right, it may be clipped at the bounds of the view. Adjust the RectF to allow for half the StrokeWidth:

mRectF.set(1, 1, mWidth - 1, mHeight - 1);
like image 125
Fletcher Johns Avatar answered Sep 17 '22 22:09

Fletcher Johns