android中绘制字符,android – 如何缩放字符以适合绘制文本的Rect?

我有一个RectList的ArrayList,以及我想要绘制到各个Rects中的字符,每个Rect一个字符.

我想拉伸文本以适应给定的Rect,填充Rect,所以我可以使用canvas.drawText()来绘制文本.

我想我需要setTextSize()和setTextScaleX()的一些组合,但我不知道从哪里开始设置参数.如何让我的角色适合Rects?

希望有人之前已经解决了这个问题,可以指出我正确的方向.

解决方法:

我最终使用approach执行此操作,使用getTextBounds来确定要使用的文本的大小和比例:

// Adjust text size to fill rect

paint.setTextSize(100);

paint.setTextScaleX(1.0f);

// ask the paint for the bounding rect if it were to draw this text

Rect bounds = new Rect();

paint.getTextBounds(words[i], 0, words[i].length(), bounds);

// get the height that would have been produced

int h = bounds.bottom - bounds.top;

// figure out what textSize setting would create that height of text

float size = (((float)(rect.height())/h)*100f);

// and set it into the paint

paint.setTextSize(size);

// Now set the scale.

// do calculation with scale of 1.0 (no scale)

paint.setTextScaleX(1.0f);

// ask the paint for the bounding rect if it were to draw this text.

paint.getTextBounds(words[i], 0, words[i].length(), bounds);

// determine the width

int w = bounds.right - bounds.left;

// calculate the baseline to use so that the entire text is visible including the descenders

int text_h = bounds.bottom-bounds.top;

int baseline =bounds.bottom+((rect.height()-text_h)/2);

// determine how much to scale the width to fit the view

float xscale = ((float) (rect.width())) / w;

// set the scale for the text paint

paint.setTextScaleX(xscale);

canvas.drawText(words[i], frame.left + rect.left * scaleX, frame.top + rect.bottom * scaleY - baseline, paint);

标签:android

来源: https://codeday.me/bug/20190709/1417933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值