Android Paint Style 如何正确画一个空心矩形

本文详细介绍如何在Android中使用Paint.Style.STROKE绘制一个精确的空心矩形,包括考虑轮廓宽度对坐标的影响,以及自定义View实现的具体代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android在用画笔的时候有三种Style,分别是
Paint.Style.STROKE 只绘制图形轮廓(描边)
Paint.Style.FILL 只绘制图形内容
Paint.Style.FILL_AND_STROKE 既绘制轮廓也绘制内容

那么如何正确画一个空心矩形呢?
比如我们现在要画一个200x200像素,轮廓宽度为40像素的空心矩形,显示效果如下,上面的粉色是宽度为200像素的view。
image.png

代码如下:

<ImageView
        android:id="@+id/imageview"
        android:layout_width="200px"
        android:layout_height="40px"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="40px"
        android:layout_below="@id/ll_top"
        android:background="#FF00FF"
        />
    <com.xiaoer.test.TestView
        android:id="@+id/testview"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageview"
        android:layout_marginLeft="40px"
        />

自定义TestView代码:

package com.xiaoer.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class TestView extends View {
    public TestView(Context context) {
        super(context);
    }


    public TestView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        RectF rectF = new RectF();
        Paint shellPaint = new Paint();
        shellPaint.setAntiAlias(true);
        shellPaint.setColor(Color.RED);
        int strokeWidth = 40;
        shellPaint.setStrokeWidth(strokeWidth);
        shellPaint.setStyle(Paint.Style.STROKE);

        rectF.left = strokeWidth/2;
        rectF.right = 200 - strokeWidth/2;
        rectF.top = strokeWidth/2;
        rectF.bottom = 200 - strokeWidth/2;

        canvas.drawRect(rectF, shellPaint);

    }
}


总结:确定坐标时要考虑轮廓的宽度,想象我们自己拿一个画笔,画笔的宽度是40px,那么我们下笔的时候肯定不是从顶端开始,而是从画笔宽度的一半开始画。

如果我们设置如下坐标值:

  rectF.left = 0;
  rectF.right = 200;
  rectF.top = 0;
  rectF.bottom = 200 ;

那么我们画出的将是这个样式:
image.png

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值