package com.canvas.paint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class mainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Canvas canvas;
public MyView(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);//設定Surface生命週期回調
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
canvas = mHolder.lockCanvas();//獲得畫布
canvas.drawColor(Color.WHITE);//設定畫布背景為白色
Paint mPaint = new Paint();
//畫矩形
mPaint.setColor(Color.YELLOW);
canvas.drawRect(100, 200, 200, 300, mPaint);
canvas.save();//每畫完一個圖做備忘儲存,以保證與其它圖形互不影響
//畫旋轉
canvas.rotate(45);//旋轉角度45度
mPaint.setColor(Color.GREEN);
canvas.drawRect(150, 10, 200, 60, mPaint);//畫矩形
canvas.save();
//畫漸層色圓形
Shader mShader=new LinearGradient(0,0,100,100,
new int[]{Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW},
null,Shader.TileMode.REPEAT);//使用著色器
mPaint.setShader(mShader);
canvas.drawCircle(500, 150, 80, mPaint);
/*
canvas.save();
//畫三角形
mPaint.setStyle(Paint.Style.STROKE);//設定空心
mPaint.setStrokeWidth(3);//設定p外框寬度
Path path=new Path();
path.moveTo(10,330);
path.lineTo(70,330);
path.lineTo(40,270);
path.close();
canvas.drawPath(path,mPaint);
canvas.save();
// 畫梯形
mPaint.setAntiAlias(true);//去掉邊緣鋸齒
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL);//設定實心
Path path1=new Path();
path1.moveTo(10,410);
path1.lineTo(70,410);
path1.lineTo(55,350);
path1.lineTo(25,350);
path1.close();
canvas.drawPath(path1,mPaint);
canvas.save();
//畫橢圓形
mPaint.setAntiAlias(true);//去掉邊緣鋸齒
mPaint.setColor(Color.RED);
RectF re=new RectF(10,220,70,250);
canvas.drawOval(re,mPaint);
*/
canvas.restore();
mHolder.unlockCanvasAndPost(canvas);//完成繪圖後解鎖遞交畫布視圖
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
}