美文网首页
Android Paint Style 如何正确画一个空心矩形

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

作者: 小二小二小二 | 来源:发表于2020-06-14 16:45 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Android Paint Style 如何正确画一个空心矩形

          本文链接:https://www.haomeiwen.com/subject/ygaxxktx.html