天天看點

android在view上畫圖,Android View自定義控件畫圖

package zenglei.com.drawing;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.RectF;

import android.util.AttributeSet;

import android.view.View;

public class MyDrawView extends View {

private Paint mPaint;

private Bitmap mBitmap;

private RectF mRectF;

private Path mPath;

private Paint mPaint2;

public MyDrawView(Context context) {

// super(context);

this(context, null);

}

public MyDrawView(Context context, AttributeSet attrs) {

super(context, attrs);

initPaint();

initPaint2();

initPath();

//加載圖檔4.畫圖檔

mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

//建立矩形6.畫扇形的

mRectF = new RectF(10,10,180,180);

}

private void initPaint() {

mPaint = new Paint();

//抗鋸齒

mPaint.setAntiAlias(true);

//顔色

mPaint.setColor(Color.RED);

//設定樣式

mPaint.setStyle(Paint.Style.STROKE);

//設定畫筆寬度

mPaint.setStrokeWidth(3);

}

private void initPaint2()

{

mPaint2 = new Paint();

mPaint2.setColor(Color.GREEN);

//設定抗鋸齒

mPaint2.setAntiAlias(true);

// 設定樣式

// mPaint2.setStyle(Paint.Style.STROKE);

// 設定畫筆的寬度

mPaint2.setStrokeWidth(3);

}

private void initPath() { //initPat需要放到

mPath = new Path();

//第一個點的位置

int x1 = 100, y1 = 10;

//第二個點位置

int x2 = 180, y2 = 180;

//第三個點的位置

int x3 = 20, y3 = 180;

//讓畫筆移動到第一個點的位置

mPath.moveTo(x1, y1);

//連接配接第二個點

mPath.lineTo(x2, y2);

//連接配接第三個點

mPath.lineTo(x3, y3);

//連接配接到第一個點

mPath.lineTo(x1, y1);

// 回路,閉合我們的圖形

mPath.close();

}

// 因為大小,位置,父控件已經幫你做了,是以這裡不需要我們自己做

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

// 1.畫直線

float startX = 10; //起始點X點

float startY = 100;//起始點Y點

float stopX = 300; //結束點X

float stopY = 100; //結束點Y

//Paint()是畫筆

// canvas.drawLine(startX,startY,stopX,stopY, mPaint);

// 2.畫圓----畫筆要打開否則是實心的

// canvas.drawCircle(100, 100, 60, mPaint);// canvas.drawCircle(圓心x,圓心y,圓的半徑,mPaint);

// 3. 畫空心圓---畫筆要打開否則是實心的

// for (int i = 10 ; i <=100 ;) { //自己調次數

// canvas.drawCircle(100, 100, i, mPaint);

// i += 10;}

// 4. 畫圖檔

// canvas.drawBitmap(mBitmap,20,20,mPaint);

// 5. 畫三角形

canvas.drawPath(mPath,mPaint); //canvas.drawPath(路徑,畫筆)

// 6. 畫扇形

// RectF oval, //矩形,需要建立對象,不妨在ondraw方法裡面

// float startAngle = 0; //其實角度

// float sweepAngle = 50;// 掃過的角度

// boolean useCenter = true; //是否繪制兩條邊

// // Paint paint //畫筆

// canvas.drawArc(mRectF, 0, 360, useCenter, mPaint);

// canvas.drawArc(mRectF, startAngle, sweepAngle, useCenter, mPaint2);

}

}