搞清canvas,paint,view的关系

Paint

Paint类包含样式和颜色有关如何绘制几何形状,文本和位图的信息,它通常跟Canvas结合起来使用的。例子:

Paint cPaint = new Paint();
cPaint.setColor(Color.LTGRAY);

 画笔的颜色预先定义成浅灰色

Canvas

Canvas类用来描绘平面图形,Canvas起初是没有任何内容的,就像投影仪的幻灯底片。

Canvas提供多个方法,可以让你画直线、矩形、圆形以及其他几何图形。在Android中,显示屏是由一个Activity来呈现的,

Activity又是通过View来填充的,View又可以通过Canvas来描绘界面。前提是你要重写View.onDraw( ),该方法唯一的一个参数就是用来画图形的canvas

这里是一个示例activity--GridActivity,它包含了一个视图TableViewGridActivity.java

public class GridActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TableView gridView = new TableView(getApplicationContext());
setContentView(gridView);
}
}
public class TableView extends View {
private static final String TAG = "Sudoku";

private float width; // width of one tile
private float height; // height of one tile

public TableView(Context context) {
super(context);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w / 9f;
height = h / 9f;
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected void onDraw(Canvas canvas) {
Paint background = new Paint();
background.setColor(Color.WHITE);
canvas.drawRect(0, 0, getWidth(), getHeight(), background);

final Paint slim = new Paint();
slim.setColor(Color.DKGRAY);
for (int i = 0; i < 9; i++) {
canvas.drawLine(0, i * height, getWidth(), i * height, slim);
canvas.drawLine(i * width, 0, i * width, getHeight(), slim);
}

final Paint foreground = new Paint();
foreground.setColor(Color.DKGRAY);
foreground.setTextSize(height * 0.75f);
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);

// Draw the number in the center of the tile
FontMetrics fm = foreground.getFontMetrics();
// Centering in X: use alignment (and X at midpoint)
float x = width / 2;
// Centering in Y: measure ascent/descent first
float y = height / 2 - (fm.ascent + fm.descent) / 2;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
String num = String.valueOf(i * 9 + j + 1);
canvas.drawText(num, j * width + x, i * height + y, foreground);
}
}
}
}

显示效果:

 搞清canvas,paint,view的关系

转载:http://www.8qiu.cn/archives/687

相关推荐