Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom view: Set canvas size to wrap bitmap

I have a custom view that has Canvas in it. I'm using this canvas to show a bitmap on it and then I can draw over the bitmap on touch. When I load the bitmap it is a lot bigger then the view size and I can't see the whole bitmap (it's picture taken with camera). I tried to create scaled bitmap and then draw it on the canvas, but in that case the bitmap is smaller and the canvas is taking the whole layout space available. I'm adding this view programmatically, not int the xml layout. I have set this to the view but not working:

fdvImage = new ImageEditingView(this, b);
RelativeLayout.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
fdvImage.setLayoutParams(lp);

and this is my view constructor:

public ImageEditingView(Context c, Bitmap b) {
    super(c);
    this.setMinimumHeight(0);

    mBitmap = Bitmap.createScaledBitmap(b, b.getWidth()/2, b.getHeight()/2, true);
    mCanvas = new Canvas(mBitmap);
}

and in the onDraw I have this:

protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
}

So, my question is: Why is the canvas taking all the layout space even if the bitmap is smaller then it?

like image 872
nikmin Avatar asked Nov 13 '22 07:11

nikmin


1 Answers

Use this code to draw bitmap

canvas.drawBitmapMesh(yourBitmap, 1, 1,vertices, 0, null, 0,
                                        paint);

Make vertices according to your view

[EDIT]

    float[] vertices = new float[8];
 vertices[0]=0; vertices[1]=0; vertices[2]=100; vertices[3]=0;
 vertices[4]=0;vertices[5]=200; vertices[6]=100; vertices[7]=200;

change the 100 to your width and 200 to height

like image 112
Arun C Avatar answered Nov 14 '22 23:11

Arun C