如何在Android中的Canvas上绘制透明边的矩形

时间:2014-07-14 10:18:44

标签: android android-layout android-canvas android-custom-view android-styles

我知道如何在Android中的Canvas上绘制矩形。我的要求是在不使用图像文件(Bitmap)的情况下在画布上绘制矩形,如下所示。

enter image description here

我如何实现它,在此先感谢。

1 个答案:

答案 0 :(得分:1)

我为此效果创建了一个示例,希望它能为您提供帮助:

runtime screenshot

public class ScanBorderView extends View {
    private int mBorderHeight;
    private int mBorderWidth;
    private int mBorderColor;
    private Rect mBounds, mDrawBounds;
    private Paint mPaint;

    public ScanBorderView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mBounds = new Rect();
        mDrawBounds = new Rect();

        mBorderWidth = 4;
        mBorderHeight = 40;
        mBorderColor = Color.RED;

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(mBorderColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mBounds.set(getPaddingLeft(), getPaddingTop(),
            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());

        // top-left
        mDrawBounds.set(mBounds);
        mDrawBounds.right = mDrawBounds.left + mBorderWidth;
        mDrawBounds.bottom = mDrawBounds.top + mBorderHeight;
        canvas.drawRect(mDrawBounds, mPaint);

        mDrawBounds.right = mDrawBounds.left + mBorderHeight;
        mDrawBounds.bottom = mDrawBounds.top + mBorderWidth;
        canvas.drawRect(mDrawBounds, mPaint);


        // top-right
        mDrawBounds.set(mBounds);
        mDrawBounds.left = mDrawBounds.right - mBorderWidth;
        mDrawBounds.bottom = mDrawBounds.top + mBorderHeight;
        canvas.drawRect(mDrawBounds, mPaint);

        mDrawBounds.left = mDrawBounds.right - mBorderHeight;
        mDrawBounds.bottom = mDrawBounds.top + mBorderWidth;
        canvas.drawRect(mDrawBounds, mPaint);


        // bottom-left
        mDrawBounds.set(mBounds);
        mDrawBounds.top = mDrawBounds.bottom - mBorderHeight;
        mDrawBounds.right = mDrawBounds.left + mBorderWidth;
        canvas.drawRect(mDrawBounds, mPaint);

        mDrawBounds.set(mBounds);
        mDrawBounds.top = mDrawBounds.bottom - mBorderWidth;
        mDrawBounds.right = mDrawBounds.left + mBorderHeight;
        canvas.drawRect(mDrawBounds, mPaint);


        // bottom-right
        mDrawBounds.set(mBounds);
        mDrawBounds.top = mDrawBounds.bottom - mBorderHeight;
        mDrawBounds.left = mDrawBounds.right - mBorderWidth;
        canvas.drawRect(mDrawBounds, mPaint);

        mDrawBounds.set(mBounds);
        mDrawBounds.top = mDrawBounds.bottom - mBorderWidth;
        mDrawBounds.left = mDrawBounds.right - mBorderHeight;
        canvas.drawRect(mDrawBounds, mPaint);
    }
}