效果如下:
创建Activity,继承View:
package com.example.day_02;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class OneActivity extends View {
Paint mPaint;
public OneActivity(Context context) {
super(context);
init();
}
public OneActivity(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
//创建、设置画笔
private void init() {
mPaint=new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(10);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(20,20,20,350,mPaint);
mPaint.setColor(Color.RED);
canvas.drawLine(20,350,500,350,mPaint);
//设置矩形
Rect rect=new Rect();
rect.top=40;
rect.bottom=350;
rect.left=50;
rect.right=100;
//设置矩形的颜色
mPaint.setColor(Color.DKGRAY);
canvas.drawRect(rect,mPaint);
Rect rect2=new Rect();
rect2.top=90;
rect2.bottom=350;
rect2.left=140;
rect2.right=180;
//设置矩形的颜色
mPaint.setColor(Color.GREEN);
canvas.drawRect(rect2,mPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
}
XML中:
<?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=".MainActivity">
<com.example.day_02.OneActivity
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />
</android.support.constraint.ConstraintLayout>