1. 程式人生 > >自定義View控制元件

自定義View控制元件

在這裡插入圖片描述
xml裡面的

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.bwie.administrator.zidingyiview.zidingyi.ZiDingYi
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

activity裡面的程式碼不需要寫
直接上自定義裡面寫的.

package com.bwie.administrator.zidingyiview.zidingyi;

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

public class ZiDingYi extends View {
    //建立一支畫筆
    private Paint mpaint;

    public ZiDingYi(Context context, AttributeSet attrs) {
        super(context, attrs);
        //初始化畫筆的操作
        initView();
    }

    private void initView() {
        mpaint = new Paint();
        //設定畫筆的顏色
        mpaint.setColor(Color.RED);
        //設定筆畫的寬度
        mpaint.setStrokeWidth(5);
        //獲取控制元件的寬高
        int height = getHeight();
        int width = getWidth();


    }

    @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);
    }

    @Override//此處是畫布
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //自定義字型的大小
        mpaint.setTextSize(40);
        //drawText  字型
        canvas.drawText("呂小布", 0, 50, mpaint);
        //drawLine 直線
        canvas.drawLine(0, 60, 300, 60, mpaint);
        //矩形類
        Rect rect = new Rect(20, 100, 150, 200);
        canvas.drawRect(rect, mpaint);

    }
}

以上.