i want my bitmap in the center of my screen..i m trying it that way but its not working...
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
int w = canvas.getWidth();
int h = canvas.getHeight();
int bw=myBitmap.getWidth();
int bh=myBitmap.getHeight();
int cx = w / 2;
int cy = h / 2;
Display d = getWindowManager().getDefaultDisplay();
int x = d.getWidth();
int y = d.getHeight();
int dx = x / 2;
int dw = y /2;
canvas.translate(cx, cy);
if (mValues != null) {
canvas.rotate(-mValues[0]);
}
int centreX = (x - bw) /2;
int centreY = (cy - bh) /2;
//canvas.drawPath(mPath, mPaint);
canvas.drawBitmap(myBitmap, centreX,centreY, null);
Here's the code you need in your view:
private int mWidth;
private int mHeight;
private float mAngle;
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
mHeight = View.MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
@Override protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
// Here's the magic. Whatever way you do it, the logic is:
// space available - bitmap size and divide the result by two.
// There must be an equal amount of pixels on both sides of the image.
// Therefore whatever space is left after displaying the image, half goes to
// left/up and half to right/down. The available space you get by subtracting the
// image's width/height from the screen dimensions. Good luck.
int cx = (mWidth - myBitmap.getWidth()) >> 1; // same as (...) / 2
int cy = (mHeight - myBitmap.getHeight()) >> 1;
if (mAngle > 0) {
canvas.rotate(mAngle, mWidth >> 1, mHeight >> 1);
}
canvas.drawBitmap(myBitmap, cx, cy, null);
}
Screenshot just for fun: http://imgur.com/EYpMJ
(Diagonal lines not part of the code posted here)
EDIT: Added NickT's solution.
EDIT 2: Changed mvalues[0] to mAngle and made it conditional. Changed divide by 2 operations to bitshifts. Remove rotation code if you don't need it.
You can try this :
int width = containerBitmap.getWidth();
int height = containerBitmap.getHeight();
float centerX = (width - centeredBitmap.getWidth()) * 0.5f;
float centerY = (height- centeredBitmap.getHeight()) * 0.5f;
You can use it to draw a bitmap at the center of another bitmap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With