Search code examples
androidandroid-canvas

Drawing canvas on framelayout


I have a frame layout with a background image.I am using canvas to draw lines on this framelayout. The issue is , on different screen sizes , the lines are not appearing at the same place.

I tried multiplying the coordinates by the screen density dpi , but its still not working.

Snippet of my canvas code

paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);

bitmap = ((BitmapDrawable) zoom_lay.getBackground()).getBitmap();
mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas = new Canvas(mutableBitmap);
canvas.drawColor(Color.TRANSPARENT);
zoom_lay.setBackground(new BitmapDrawable(getResources(), mutableBitmap));

final Path pathPolygon_2 = new Path();
pathPolygon_2.reset(); // only needed when reusing this path for a new build
canvas.drawLine(500,500,600,615,paint);

Thank you


Solution

  • Create your layout with the following params:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/mainView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@mipmap/background"
            tools:context=".MainActivity">
    

    Can be any type, FrameLayout is just an example. The important part is to set it's width and height to match parent. From there you can use your code to get the bitmap and draw on it only thing, let's say you want to draw the line horizontally in the center:

    canvas.drawLine(0,muteableBitmap.getHeight()/2,muteableBitmap.getWidth(),muteableBitmap.getHeight()/2,paint);
    

    And say you want a line vertically from the center:

    canvas.drawLine(muteable.getWidth()/2,0,muteableBitmap.getWidth()/2,muteableBitmap.getHeight,paint);
    

    I've written this manually so it might not compile due to capital letters and such, but it should work