How to align center a bitmap?

后端 未结 2 866
深忆病人
深忆病人 2021-01-02 11:00

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


        
相关标签:
2条回答
  • 2021-01-02 11:48

    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.

    0 讨论(0)
  • 2021-01-02 12:01

    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.

    0 讨论(0)
提交回复
热议问题