5.6

所花时间(包括上课):1

打码量(行):100

博客量(篇):1

了解到知识点:学习画笔和画布

 

package com.example.myapp;

 

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.util.AttributeSet;

import android.view.View;

 

import androidx.annotation.Nullable;

 

public class MyCustomView extends View {

 

    private Paint paint;

 

    public MyCustomView(Context context) {

        super(context);

        init();

    }

 

    public MyCustomView(Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);

        init();

    }

 

    public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

        init();

    }

 

    private void init() {

        paint = new Paint();

        paint.setColor(Color.BLUE);

        paint.setStyle(Paint.Style.FILL);

        paint.setStrokeWidth(5f);

    }

 

    @Override

    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        // 绘制一个蓝色的圆

        canvas.drawCircle(200, 200, 100, paint);

 

        // 改变画笔颜色

        paint.setColor(Color.RED);

        // 绘制一条红色的线

        canvas.drawLine(50, 50, 350, 350, paint);

 

        // 改变画笔样式

        paint.setStyle(Paint.Style.STROKE);

        paint.setColor(Color.GREEN);

        // 绘制一个绿色的矩形

        canvas.drawRect(100, 100, 300, 300, paint);

    }

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

 

    <com.example.myapp.MyCustomView

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

 

</RelativeLayout>

posted @ 2024-05-06 22:00  赵千万  阅读(1)  评论(0编辑  收藏  举报