我是Android开发的新手,正在尝试制作一个简单的应用程序。用户可以选择一张图片并在上面添加文字,用户可以选择不同的字体和文本大小。为了预览,我在RelativeLayout中使用ImageView,在布局中创建的文本将通过代码(使用TextView)添加到布局中。当用户点击保存按钮时,图像将与文本一起保存。
所有问题都出现在Canvas.drawText中。我找不到一个好的公式来计算正确的X和Y。绘制文本后始终处于错误的位置。Y位置始终取决于字体,并且X也会产生小缩进。
这里是屏幕截图(第一个是TextView,下面是绘制的文本):
这是我用于查找位置的代码:
public float[] getPosition(ImageView imageView, TextView textView) {
Matrix matrix = new Matrix();
imageView.getImageMatrix().invert(matrix);
float[] coord = {textView.getX(), textView.getY()+textView.getHeight()};
matrix.mapPoints(coord);
return coord;
}
这里是绘制的代码:
float[] coord = bundle.getFloatArray("coord");
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTypeface(fontsList.get(bundle.getInt("font")));
paint.setAlpha((int)(255*bundle.getFloat("alpha")));
paint.setTextSize(bundle.getFloat("size")*bundle.getFloat("scale"));
paint.setColor(bundle.getInt("color"));
canvas.drawText(text, coord[0],coord[1],paint);