最近在做使用者引導功能,該功能用了大量的畫筆操作,是以在此記錄下 Paint和 Canves 的用法。
//先定義畫筆
Paint mPaint = new Paint();
mPaint.setColor(Color.BLACK); //設定畫筆顔色
Canves 畫線
mPaint.setStyle(Paint.Style.FILL); //設定畫筆模式為填充
mPaint.setStrokeWidth(2f); //設定畫筆寬度
canvas.drawLine(startX,startY,endX,endY,mPaint);
Canves 畫矩形
mPaint.setStyle(Paint.Style.STROKE); //設定畫筆模式空心 FILL為實心
Rect rect = new Rect(left,top,right,bottom);
canvas.drawRect(rect,mPaint);//畫空心矩形
Canves 畫圓
mPaint.setStyle(Paint.Style.STROKE); //設定畫筆模式空心 FILL為實心
canvas.drawCircle(x,y,d,paint);//x y 為圓心點 d為圓半徑
Canves 畫文本
mPaint.setTextAlign(Paint.Align.CENTER);//設定文字的對齊方式
mPaint.setTextSize(sp2px(15));//設定文字大小 因為做适配是以用了sp2px的轉換
canvas.drawText("測試文字",x , y, mPaint);
//如果要畫的文字在 上面的矩形中 那麼需要判斷y的位置
Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();//獲得文字的大小 設定過字型大小後需要重新獲得
int baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;// baseline 為畫文字時候的 y
canvas.drawText("測試文字",(rect.left+rect.right)/2, baseline, mPaint);
因為用canvas畫的時候通常是按像素畫的 是以需要下面的 方法進行轉換 适配不同分辨率的機型 方法中的 this 需要換成實際應用中的 context
/**
* dp機關轉換為px
*/
public int dp2px( float dpValue){
return (int)(dpValue * (this.getResources().getDisplayMetrics().density) + 0.5f);
}
/**
* px機關轉換為dp
*/
public int px2dp( float pxValue){
return (int)(pxValue / (this.getResources().getDisplayMetrics().density) + 0.5f);
}
/**
* sp轉換成px
*/
private int sp2px( float spValue){
float fontScale=this.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue*fontScale+0.5f);
}
/**
* px轉換成sp
*/
private int px2sp( float pxValue){
float fontScale=this.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue/fontScale+0.5f);
}