如何在不改变位置

时间:2015-05-12 18:59:40

标签: android matrix bitmap imageview

我必须旋转180°的位图。问题是,位图旋转但位置不同。

没有旋转它看起来像这样: enter image description here

使用旋转它看起来像这样: enter image description here

这是我的代码:

geste_Bitmap = gesture.toBitmap ( width, height, 100, Color.YELLOW );
                   Bitmap gedrehte_Geste = rotatePicture(geste_Bitmap, width, height, imageView);


                   //  rotatePicture2(geste_Bitmap, imageView);
                     imageView.setImageBitmap(gedrehte_Geste);


private Bitmap rotatePicture(Bitmap bitmapOrg, int width, int height, ImageView imageView){


    int viewWidth = imageView.getMeasuredWidth();
    int viewHeight = imageView.getMeasuredHeight();
    float px = viewWidth/2;
    float py = viewHeight/2;


    Matrix matrix = new Matrix();

    matrix.postTranslate(-bitmapOrg.getWidth() / 2, -bitmapOrg.getHeight() / 2);
    matrix.postRotate(180);
    matrix.postTranslate(px, py);



    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);

    Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);


    return rotatedBitmap;
}

我将代码更改为以下内容,因为pxpy为0但未进行任何更改:

private void rotatePicture(final Bitmap bitmapOrg, final int width, final int height, final ImageView imageView){

    ViewTreeObserver vto = imageView.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

        @Override
        public boolean onPreDraw() {

            int viewWidth = imageView.getMeasuredWidth();
            int viewHeight = imageView.getMeasuredHeight();
            float px = viewWidth / 2;
            float py = viewHeight / 2;

            Log.d("px", "px " + px + "|" + py + bitmapOrg.getWidth());

            Matrix matrix = new Matrix();

            matrix.postTranslate(-px, -py);
            matrix.postTranslate(-bitmapOrg.getWidth() / 2, -bitmapOrg.getHeight() / 2);
            matrix.postRotate(180);
            matrix.postTranslate(bitmapOrg.getWidth() / 2, bitmapOrg.getHeight() / 2);
            matrix.postTranslate(px, py);



            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);

            Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

            imageView.setImageBitmap(rotatedBitmap);
            return true;
        }
    });


}

非常感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

Matrix matrix = new Matrix();
matrix.postRotate(180, bitmapOrg.getWidth() / 2, bitmapOrg.getHeight() / 2);
matrix.postTranslate(px, py);