自定义控件文字居中

自定义控件文字居中_第1张图片

绘制文字的x,y坐标是baseline左端点的坐标,原来一直理解为了文字的左上角,今天亲测才发现,

文字的x坐标号计算:(控件宽度-文字宽度)/2

文字的y坐标计算:控件高度/2+距离baseline的那段距离(-(decent+ascent)/2

android绘制文字时以baseline为y轴0坐标线,向上为负,向下为正,所以文字的一半正好是(decent+asecnt)/2,

文字要居中,文字的横向中心线必然与控件的横向中心线重合,而中心线的距离baseline的距离便是(decent+ascent)/2

这个值是负数,所以(控件高度/2)加上它的时候要取它的相反数。

class fontText  extends View {

    Paint accentPaint,baselinePaint,decentPaint,textPaint;

    float x=60,y=60;

    public fontText(Context context) {
        super(context);
        initPaint();
    }

    public fontText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public fontText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
         initPaint();
    }

    private void initPaint(){

        accentPaint=new Paint();
        accentPaint.setColor(Color.BLUE);

        baselinePaint=new Paint();
        baselinePaint.setColor(Color.BLACK);

        decentPaint=new Paint();
        decentPaint.setColor(Color.RED);

        textPaint=new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(20);
        textPaint.setAntiAlias(true);

    }


    @Override
    protected void onDraw(Canvas canvas) {
        Paint.FontMetrics metrics=textPaint.getFontMetrics();
        float ascent= metrics.ascent;
        float decent=metrics.descent;
        String text="hguqpwm睡觉啊";
        float width=textPaint.measureText(text);
        y=getMeasuredHeight()/2-(decent+ascent)/2;
        x=(getMeasuredWidth()-width)/2;
        canvas.drawText(text,x,y,textPaint);
        canvas.drawLine(x, y + ascent, x + width, y + ascent, accentPaint);
        canvas.drawLine(x, y + decent, x + width, y + decent, decentPaint);
        canvas.drawLine(x,y,x+width,y,textPaint);
        textPaint.setTextSize(40);
        canvas.drawLine(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, textPaint);
        canvas.drawLine(getMeasuredWidth()/2,0,getMeasuredWidth()/2,getMeasuredHeight(),textPaint);


    }



你可能感兴趣的:(android)