布局:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="com.example.day_0330_view.MainActivity"> <com.example.day_0330_view.OtherView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.constraint.ConstraintLayout>
编写自定义View类
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class OtherView extends View{ public OtherView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //渲染文本,Canvas类除了上面的还可以描绘文字, // 参数一是String类型的文本,参数二x轴, // 参数三y轴,参数四是Paint对象。 Paint paint = new Paint(); paint.setColor(Color.RED); canvas.drawText("我是自定的文本",100,100,paint); //画线,参数一起始点的x轴位置,参数二起始点的y轴位置,参数三终点的x轴水平位置, // 参数四y轴垂直位置,最后一个参数为Paint 画刷对象 canvas.drawLine(60, 40, 100, 40, paint);// 画线 canvas.drawLine(110, 40, 190, 80, paint);// 斜线 //画点,参数一水平x轴,参数二垂直y轴,第三个参数为Paint对象。 canvas.drawPoint(20,30,paint); canvas.drawRect(60, 60, 80, 80, paint);// 正方形 canvas.drawRect(60, 90, 160, 100, paint);// 长方形 } }