使用Canvas.drawText从Bitmap上的TextView错误的Y坐标

时间:2016-04-19 06:38:35

标签: java android android-canvas

请帮我解决问题或至少给我建议。 我有ImageView与覆盖TextView。用户可以将文本拖动到图像上的任何位置。之后,我想在选定的位置保存带有文字的图像。

布局(TextView动态添加到根元素):

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/root"
android:padding="0dp"
android:layout_margin="0dp">
<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:adjustViewBounds="true"
    android:scaleType="centerInside"/>
</FrameLayout>
</LinearLayout>

Y坐标中的所有问题总是错误的。我试着用2个函数找到X和Y坐标。

首先:

public float[] getPosition(ImageView imageView, TextView textView) {
Matrix matrix = new Matrix();
imageView.getImageMatrix().invert(matrix);
float[] coord = {textView.getX(), textView.getY()};
matrix.mapPoints(coord);

return coord;
}

更好的一个,使用此功能可以为您提供准确的X.

private float[] getCoordinates(ImageView iv, Bitmap bm, float x, float y){
    float projectedX = (float) ((double)x * ((double)bm.getWidth()/(double)iv.getWidth()));
    float projectedY = (float) ((double)y * ((double)bm.getHeight()/(double)iv.getHeight()));

    return new float[]{projectedX, projectedY};
}

有什么建议吗?当Canvas绘制文本时,Y始终高于所需位置。

这是我为Canvas.drawText保存数据的代码:

Bundle bundle = new Bundle();
                    TextView textView = (TextView)relativeLayout.getChildAt(i);
                    bundle.putString("text", ((TextView) relativeLayout.getChildAt(i)).getText().toString());
                    bundle.putFloatArray("coord", getPosition(imageView,textView));
                    bundle.putFloat("size", size*scale);
                    new AsyncDraw().execute(bundle);

在AsyncTask之后:

     Bundle bundle = bundles[0];
        String text = bundle.getString("text");
        float[] coord = bundle.getFloatArray("coord");
        Canvas canvas = new Canvas(oriented);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(bundle.getFloat("size"));
        canvas.drawText(text, coord[0],coord[1],paint);

1 个答案:

答案 0 :(得分:1)

尝试使用TypedValue.applyDimension方法

将高度值映射到设备屏幕指标
相关问题