Rob*_*ith 3 android draw android-canvas
我必须在地图视图上放置标记并在标记上写一个数字.我已经这样做了,但文本对齐方式因不同分辨率而异.下面是参考代码
float xVal = (float) curScreenCoords.x; // Point curScreenCoords
float yVal = (float) curScreenCoords.y-20; // Point curScreenCoords
Bitmap bitmap = BitmapFactory.decodeResource ( context.getResources() , ( R.drawable.pin_number ) ) ;
canvas.drawBitmap(bitmap, xVal, yVal, getInnerPaint());
public Paint getInnerPaint() {
if (innerPaint == null) {
innerPaint = new Paint();
}
innerPaint.setARGB(255, 117, 161, 220); // blue
innerPaint.setAntiAlias(true);
innerPaint.setStyle(Style.FILL);
return innerPaint;
}
canvas.drawText(String.valueOf(10), xVal+20, yVal+22, getCountPaint()); // 10 is just for example, it can vary to one digit to two to three
public Paint getCountPaint() {
if (innerPaint == null) {
innerPaint = new Paint();
}
innerPaint.setARGB(255, 255, 255, 255);
innerPaint.setAntiAlias(true);
innerPaint.setStyle(Style.FILL);
innerPaint.setTextSize(12f);
innerPaint.setTextAlign(Align.CENTER);
return innerPaint;
}
Run Code Online (Sandbox Code Playgroud)
一切正常,除了文本对齐,此代码适用于480*800分辨率.文本在画布中完全居中对齐.x,y位置在图像上是完美的,但在320*480上看起来并不完美.文本的x和y位置在此分辨率上看起来不同.任何人都可以建议我究竟发生了什么错误?在不同尺寸的设备上做同样的事情还有什么基础吗?提前致谢.
我认为您可以测量文本在画布中写入后的宽度和高度,然后使用它来居中.就像是:
String text = "whatever";
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
canvas.drawText(text, (canvas.getWidth() - bounds.width()) / 2, (canvas.getHeight() - bounds.height()) / 2, paint);
Run Code Online (Sandbox Code Playgroud)
嗨,我猜上面给出的答案都不够好,所以我发布我的答案试试看,所有设备都可以使用并且根本不复杂
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//paint.setTextAlign(Align.CENTER);
paint.setColor(activity.getResources().getColor(R.color.white));
paint.setTextSize(30);
// draw text to the Canvas center
Rect boundsText = new Rect();
paint.getTextBounds(String.valueOf(cluster.getMarkerList().size()), 0,
String.valueOf(cluster.getMarkerList().size()).length(), boundsText);
int x = (bitmap.getWidth() - boundsText.width()) / 2;
int y = (bitmap.getHeight() + boundsText.height()) / 2;
canvas.drawText(String.valueOf(cluster.getMarkerList().size()), x, y, paint);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4787 次 |
| 最近记录: |