You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何利用RectF绘制矩形周边的全部区域?

可以通过RectF实现这个需求

核心思路是通过RectF定义矩形周边的区域,再完成绘制。这里提供两种简洁的实现方式:

方式一:先填充整体再覆盖中间

先把整个View区域用周边色填充,再用目标矩形的颜色覆盖中间部分,剩余区域就是需要的周边区域,代码更简洁:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 假设你已有的目标矩形
    RectF targetRect = new RectF(100, 100, 500, 500);
    // 自定义View的整体范围
    RectF viewFullRect = new RectF(0, 0, getWidth(), getHeight());

    // 周边区域的绘制画笔
    Paint borderPaint = new Paint();
    borderPaint.setColor(Color.parseColor("#FF5722"));
    // 中间矩形的绘制画笔
    Paint rectPaint = new Paint();
    rectPaint.setColor(Color.parseColor("#FFFFFF"));

    // 绘制整个View的周边色
    canvas.drawRect(viewFullRect, borderPaint);
    // 绘制中间矩形,覆盖掉中间区域
    canvas.drawRect(targetRect, rectPaint);
}

方式二:拆分周边为四个独立RectF

如果需要给不同方向的周边区域设置不同颜色,可以把周边拆分为左、上、右、下四个RectF,分别绘制:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    RectF targetRect = new RectF(100, 100, 500, 500);
    int viewWidth = getWidth();
    int viewHeight = getHeight();

    // 按需给不同区域设置颜色
    Paint leftPaint = new Paint();
    leftPaint.setColor(Color.parseColor("#FF5722"));
    Paint topPaint = new Paint();
    topPaint.setColor(Color.parseColor("#2196F3"));
    Paint rightPaint = new Paint();
    rightPaint.setColor(Color.parseColor("#FFC107"));
    Paint bottomPaint = new Paint();
    bottomPaint.setColor(Color.parseColor("#4CAF50"));

    // 定义四个周边区域的RectF
    RectF leftArea = new RectF(0, 0, targetRect.left, viewHeight);
    RectF topArea = new RectF(targetRect.left, 0, targetRect.right, targetRect.top);
    RectF rightArea = new RectF(targetRect.right, 0, viewWidth, viewHeight);
    RectF bottomArea = new RectF(0, targetRect.bottom, viewWidth, viewHeight);

    // 分别绘制四个区域
    canvas.drawRect(leftArea, leftPaint);
    canvas.drawRect(topArea, topPaint);
    canvas.drawRect(rightArea, rightPaint);
    canvas.drawRect(bottomArea, bottomPaint);
}

内容的提问来源于stack exchange,提问作者testivanivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:31:10