Android之Canvas的drawRoundRect()

1 问题

Canvas的drawRoundRect()函数怎么用

public void drawRoundRect(RectF rect, float rx, float ry, Paint paint)
功能:该方法用于在画布上绘制圆角矩形,通过指定RectF对象以及圆角半径来实现。

float rx:生成圆角的椭圆的X轴半径
float ry:生成圆角的椭圆的Y轴半径

 

2 代码实现

 TestView.java文件如下

package com.onemt.sdk.circle;

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.NonNull;
import androidx.annotation.Nullable;

public class TestView extends View {


    private Paint mPaint;
    private RectF rectf;
    public TestView(@NonNull Context context) {
        super(context);
        init();
    }

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

    public TestView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        mPaint.setColor(Color.GRAY);
        rectf = new RectF(0f, 0f, 800f, 600f);
        canvas.drawRect(rectf, mPaint);

        mPaint.setColor(Color.BLACK);
        canvas.drawRoundRect(rectf, 200f, 200f, mPaint);

        mPaint.setColor(Color.RED);
        canvas.drawCircle(200f, 200f, 200f, mPaint);

    }

}

 activity_main.xml文件如下

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.onemt.sdk.circle.TestView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

3 效果如下

发布了1073 篇原创文章 · 获赞 678 · 访问量 301万+

猜你喜欢

转载自blog.csdn.net/u011068702/article/details/105020351