evansir
evansir

Reputation: 1

Wrong Y coordinate from TextView on Bitmap using Canvas.drawText

Please help me with my problem or at least give me advice. I have ImageView with overlayed TextView. The user can drag text to any position on the image. After, I want to save the image with text at chosen position.

Layout (TextView add dynamically to root element):

<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>

All problem in Y coordinate is always wrong. I'm try 2 function to find X and Y coordinates.

First:

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;
}

and better one, using this function give you accurate 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};
}

Any advice? Y always higher than the desired position when Canvas draw text.

Here is my code to save data for 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);

And after in 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);

Upvotes: 0

Views: 170

Answers (1)

Mina Wissa
Mina Wissa

Reputation: 10971

Try mapping the height values to your device screen metrics using TypedValue.applyDimension method

Upvotes: 1

Related Questions