以下是一个使用 Canvas 绘制直角三角形的实例代码:

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

public class TriangleView extends View {

    private Paint paint;

    public TriangleView(Context context) {
        super(context);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);
    }

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

        int width = getWidth();
        int height = getHeight();

        // 绘制直角三角形的三个点坐标
        float x1 = 0;
        float y1 = height;
        float x2 = width;
        float y2 = height;
        float x3 = 0;
        float y3 = 0;

        // 绘制直角三角形
        canvas.drawPath(createTrianglePath(x1, y1, x2, y2, x3, y3), paint);
    }

    // 创建直角三角形的 Path 路径
    private Path createTrianglePath(float x1, float y1, float x2, float y2, float x3, float y3) {
        Path path = new Path();
        path.moveTo(x1, y1);
        path.lineTo(x2, y2);
        path.lineTo(x3, y3);
        path.close();
        return path;
    }
}

在 Activity 中使用这个自定义的 View:

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        TriangleView triangleView = new TriangleView(this);
        setContentView(triangleView);
    }
}

在布局文件中添加一个占满整个屏幕的 FrameLayout 容器:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

这样就可以在手机屏幕上绘制一个直角三角形了。

Android Canvas 绘制直角三角形实例代码

原文地址: https://www.cveoy.top/t/topic/btpX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录