gpt4 book ai didi

java - 使用 Canvas.drawText 从位图上的 TextView 获取错误的 Y 坐标

转载 作者:行者123 更新时间:2023-12-01 10:02:13 25 4
gpt4 key购买 nike

请帮助我解决我的问题,或者至少给我建议。我有 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);

最佳答案

尝试使用 TypedValue.applyDimension 将高度值映射到您的设备屏幕指标方法

关于java - 使用 Canvas.drawText 从位图上的 TextView 获取错误的 Y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com