在画板上画矩形,在矩形中画字


创建一个类MyGridView该类继承View

public class MyGridView extends View{
    public MyGridView(Context context){
        super(context);
        }
}

    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

        //绘制字
        Paint textPaint = new Paint();
        textPaint.setTextAlign(Align.CENTER);
        textPaint.setColor(Color.GRAY);
        textPaint.setTextSize(75);
        //绘制矩形
        canvas.drawRect(20,20,120,120,textPaint);
        //绘制文字
        textPaint.setColor(Color.GREEN);
        float x = (120 -20) / 2;

        //定义字体规格
        FontMetrics fm = textPaint.getFontMetrices();
        float y = (120 20) / 2 - (fm.ascent + fm.descent) / 2;
        canvas.drawText("中",20 + x, 20 + y, textPaint);
    }