Neil Walker
Neil Walker

Reputation: 6848

Having some problems with scaling in Android custom view

I've created a simple custom control in android and on it I place a background image. I'm having problems when the control is placed on a layout at different sizes (i.e. when it is stretched), specifically:

  1. I wish to overlay a rectangle at a specific position and size, which I know the pixel position for the original image. How can I do this with my control. I suspect something like this is impossible given it's a 9-patch. Is my best bet to work out the percentage from the top/left on the original or is that pointless given some parts stretch and some don't?

  2. In the custom control I set the image like this in the constructor:

    setBackgroundResource(R.drawable.buttonbt);

Which is working just fine, however I wanted to originally draw it in the onDraw event as I might want to change it depending on property changes, e.g.

Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.buttonbt);
canvas.drawBitmap(b, 0, 0, null);

But this does not resize according to the size of its bounding box, it is simply trying to show it at it's original size without scaling to fit. How would you do this (whether the former method is better or not).

thanks.

Upvotes: 0

Views: 423

Answers (2)

pskink
pskink

Reputation: 24720

ok when your View is say 100x100 px and your Bitmap is 300x300 you can try the following (pseudo code here) in inDraw method:

# src is a Bitmap 300x300
# dst is a View 100x100
mMatrix.setRectToRect(RectF src, RectF dst, Matrix.ScaleToFit stf)
canvas.save()
canvas.concat(mMatrix)
canvas.drawBitmap(mBitmap, 0, 0, null)
// actually it will draw a rect with left/top edge at (10, 10) and right/bottom at (20, 20)
canvas.drawRect(30, 30, 60, 60, paint)
canvas.restore()

Upvotes: 0

user3513843
user3513843

Reputation:

You can create a scaled bitmap as below

Bitmap bitmap = Bitmap.createScaledBitmap(b, width, height, true);

Hope it will work for you. Please let me know!

Upvotes: 1

Related Questions