android - 如何让边框更平滑

标签 android draw rect

我想为 View 添加边框,边框宽度、颜色、半径可以由用户设置。所以我试着为它画一个矩形。我用drawRoundRect画的时候,拐角处的线不光滑,比其他地方粗。我不知道如何解决它。请给我一些指示。还有其他方法吗?我必须使用代码来绘制它。

非常感谢。 附加代码:矩形的红色角。 过去的代码:

public class MPCTextView extends TextView {
    // private Context context;
    private final static String TAG = "MPCTextView";
    public final static int DEFAULT_BACKGROUND_COLOR = Color
            .parseColor("#28FF28");
    public final static int DEFAULT_BORDER_COLOR = Color.parseColor("#FF0000");

    public int mBoderWidth = 2;
    public int mBoderColor;
    public int mBoderRadius = 20;
    public int mbackgroundColor;
    public boolean isHaveBorder = true;
    public boolean isHaveBackground = true;
    RectF mRectF = new RectF();
    Rect mRec = new Rect();
    Paint mPaint = new Paint();

    public MPCTextView(Context context) {
        super(context);
        // this.context = context;
    }

    @Override
    protected void onDraw(Canvas canvas) {

        // try to add a boder for this view.
        canvas.getClipBounds(mRec);

        // draw background
        // canvas.drawColor(mbackgroundColor);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(DEFAULT_BACKGROUND_COLOR);
        if (mBoderRadius > 0) {
            mRectF.set(mRec);
            canvas.drawRoundRect(mRectF, mBoderRadius, mBoderRadius, mPaint);

        } else {
            canvas.drawRect(mRec, mPaint);
        }

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mBoderWidth);
        mPaint.setColor(DEFAULT_BORDER_COLOR);
                mPaint.setAntiAlias(true);

        if (mBoderRadius > 0) {
            mRectF.set(mRec);
            canvas.drawRoundRect(mRectF, mBoderRadius, mBoderRadius, mPaint);

        } else {
            canvas.drawRect(mRec, mPaint);
        }

        super.onDraw(canvas);

    }

enter image description here

最佳答案

问题的核心是填充,而不是抗锯齿。角并没有变粗,而是正常的宽度。但是,直线被剪掉了。

如果将描边宽度设置为 2,则真正的直线宽度为 1,因为描边是矩形,轴是线 x = 0。这意味着矩形是 (left=0,up=-1,right =length,bottom=1),但是up-1在canvas之外,所以不会被绘制。角是全宽的,因为它在 Canvas 中。

因此,您只需要设置内边距即可。

下面是使圆角矩形完全绘制在 Canvas 内的代码:

float pad = 1f;
mRectF.set(new RectF(mRec.left + pad, mRec.top + pad, mRec.right - pad, mRec.bottom - pad));
canvas.drawRoundRect(mRectF, mBoderRadius, mBoderRadius, mPaint);

关于android - 如何让边框更平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750329/

相关文章:

image - Canvas drawImage 在 CustomPainter 中缩放高度和宽度

java - 在 Android 中从没有像素透明度的 Drawable 创建形状

javascript - Canvas 矩形具有相同的 x 和 y,但不应如此

android - 使用 YuvImage 压缩时出现奇怪的错误

Android 使用 JNI 而不使用静态变量

android - RxJava 和 Retrofit - Rx 的第一步

android - 从 IntentService 更新进度条?

c# - 使用 C# 和 Visual Studio 创建可以动态更改其形状和位置的形状

swift 3 : Drawing a rectangle

Android Dagger 和 Firebase