11.16
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>
本文来自博客园,作者:赵千万,转载请注明原文链接:https://www.cnblogs.com/zhaoqianwan/p/18162577
千万千万赵千万
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步