简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM