1.整體概括: 用"button的繪製"做為執行個體.
public class MyButton extends Button {--->繼承Button. 一般我們都繼承View,沒有樣式
public MyButton(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {--->activity載入的時候會自動調用該方法
super.onDraw(canvas);
Paint paint = new Paint();--->畫筆:具有顏色和樣式等
paint.setColor(Color.RED);
canvas.drawCircle(30, 30, 30, paint);--->畫布: 具有繪製相關方法.
}
}
2.各種圖形的繪製
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//畫直線.
paint.setColor(Color.RED);
canvas.drawLine(0, 0, 100, 100, paint);
//畫圓
paint.setColor(Color.YELLOW);
paint.setStyle(Style.STROKE);//--->設定描邊
paint.setStrokeWidth(3);
canvas.drawCircle(30, 30, 40, paint);
//畫矩形
paint.setColor(Color.GREEN);
canvas.drawRect(102, 102, 150, 150, paint);
//畫橢圓
paint.setColor(Color.BLUE);
paint.setStrokeWidth(1);
RectF oval = new RectF(160, 160, 400, 250);
canvas.drawOval(oval, paint);
//畫圓角矩形.
paint.setColor(Color.CYAN);
canvas.drawRoundRect(oval, 20, 30, paint);
//畫弧
paint.setColor(Color.WHITE);
canvas.drawArc(oval, 90, 200, true, paint);
//畫路徑
paint.setColor(Color.GRAY);
Path path = new Path();
path.moveTo(10, 170);
path.lineTo(40, 170);
//FIXME 這裡畫的x值必須比上一個小? 必須為銳角?
path.lineTo(60, 180);
path.close();
canvas.drawPath(path, paint);
}
3.畫Text和Bitmap
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//畫TEXT.這個設定的10,10是按照Text左下角的座標來顯示的.
paint.setColor(Color.RED);
canvas.drawText("this is my drawText", 10, 10, paint);
//畫TEXT在path.
Path path = new Path();
path.moveTo(50, 50);
path.lineTo(100, 100);
path.lineTo(100, 150);
canvas.drawPath(path, paint);
paint.setColor(Color.YELLOW);
canvas.drawTextOnPath("this is my draw use drawTextOnPath", path, 0, 0, paint);
//畫Bitmap(這個方法相當於切割)
// Bitmap bitmap=((BitmapDrawable) (getResources().getDrawable(R.drawable.ic_launcher))).getBitmap();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);//上面那種方法也行.
Rect src = new Rect(0, 0, 30, 30);
RectF dst = new RectF(11, 11, 60, 60);
canvas.drawBitmap(bitmap, src, dst, paint);
//畫Bitmap(這回用matrix:就是整圖片的一些旋轉,平移啥用的)
matrix.setRotate(60);
matrix.setScale(3, 3);
matrix.setSkew(1, 0);
matrix.setTranslate(100, 100);
//matrix的三種方法set, pre, post. 用set後面的會覆蓋前面的.用pre是在set之前.用post是在set之後.多個pret 和post不會產生覆蓋.
matrix.preScale(1, 3);
matrix.postRotate(90, 200, 200);
canvas.drawBitmap(bitmap, matrix, paint);
}