canvas.drawText 以(cx,cy)为中心,写字

18 篇文章 0 订阅
8 篇文章 0 订阅



画一个圆,圆心为(cx,cy),并以此为中心,写数字:

通常情况下,drawText(text,cx,xy,paint)中,点(cx,cy)是文字的起始点,如下:



即使使用paint.setTextAlign(Paint.Align.CENTER),是文字横向居中,但是纵向不会居中。如果能得到文字高度,再向下位移一半,就可以居中了:

先要取得text的边界,paint.getTextBounds(,,,textBounds);

取得了边界,就可计算高度,宽度。



Paint countPaint = new Paint(Paint.ANTI_ALIAS_FLAG
				| Paint.DEV_KERN_TEXT_FLAG);
		countPaint.setColor(Color.BLUE);
		countPaint.setTextSize(20f);
		countPaint.setTypeface(Typeface.DEFAULT_BOLD);
		countPaint.setTextAlign(Paint.Align.CENTER);
		Rect textBounds = new Rect();
		String numberStr = String.valueOf(number);
		countPaint.getTextBounds(numberStr, 0, numberStr.length(), textBounds);//get text bounds, that can get the text width and height
		int textHeight = textBounds.bottom - textBounds.top;
		Log.i("TAG","bounds: left = "+textBounds.left + ", right = "+textBounds.right+", top = "+textBounds.top+", bottom = "+textBounds.bottom);
		canvas.drawText(numberStr, cx, cy + textHeight/2,
				countPaint);

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值