Android自定义控件---DrawText 基线的确定

本文详细介绍如何在自定义Android View中确定DrawText方法使用的基线坐标,包括计算基线Y坐标的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DrawText 基线的确定

上一篇写了自定义View的入门案例,里面涉及到一个知识点,基线的确定,这里做一个详细说明。
Android自定义View入门—自定义一个TextView

在自定义控件的时候,有时候会用到DrawText 方法.

这里我把上一篇自定义TextView的贴出来

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

        int x = getPaddingLeft();

        //dy 代表的是:高度的一半到 baseLine的距离
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        // top 是一个负值  bottom 是一个正值    top,bttom的值代表是  bottom是baseLine到文字底部的距离(正值)
        // 必须要清楚的,可以自己打印就好
        int dy = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        int baseLine = getHeight()/2 + dy;

        canvas.drawText(costom_text,x,baseLine,paint);
    }
/**
     * Draw the text, with origin at (x,y), using the specified paint. The
     * origin is interpreted based on the Align setting in the paint.
     *
     * @param text  The text to be drawn
     * @param x     The x-coordinate of the origin of the text being drawn
     * @param y     The y-coordinate of the baseline of the text being drawn
     * @param paint The paint used for the text (e.g. color, size, style)
     */
    public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
        native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags,
                paint.getNativeInstance(), paint.mNativeTypeface);
    }

x,y 分别表示 基线的开始坐标,并不是 文字左上角的坐标,因为文字的绘制是以基线为基础的

这里写图片描述

图中的 五角星 所在的线 就是基线 BaseLine,那么如何确定基线的x,y坐标呢?

首写我们先确定一下x坐标 :int x = getPaddingLeft(); 也就是文字距左边的距离

y坐标:

1、我们先计算一下文字高度的一半到 baseLine的距离。

int dy = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;

2、之后我们再使用控件高度的一般,加上文字高度的一半到 baseLine的距离,就是基线的y坐标
int baseLine = getHeight()/2 + dy;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值