Android 图片旋转

旋转图片通常的方法:

  public static Bitmap rotateBitmap(int degree, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

但是找到另一种方法,根据网上的方法改的,网络上的只支持90度旋转,其他角度有问题。但是改造后只支持90、270、360以及其负值的角度旋转:

 private static Bitmap rotateBitmap2(Bitmap bm, int orientationDegree) {
        //方便判断,角度都转换为正值
        int degree = orientationDegree;
        if( degree < 0){
            degree = 360 + orientationDegree;
        }

        int srcW = bm.getWidth();
        int srcH = bm.getHeight();

        Matrix m = new Matrix();
        m.setRotate(degree, (float) srcW / 2, (float) srcH / 2);
        float targetX, targetY;

        int destH = srcH;
        int destW = srcW;

        //根据角度计算偏移量,原理不明
        if (degree == 90 ) {
            targetX = srcH;
            targetY = 0;
            destH = srcW;
            destW = srcH;
        } else if( degree == 270){
            targetX = 0;
            targetY = srcW;
            destH = srcW;
            destW = srcH;
        }else if(degree == 180){
            targetX = srcW;
            targetY = srcH;
        }else {
            return bm;
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        //注意destW 与 destH 不同角度会有不同
        Bitmap bm1 = Bitmap.createBitmap(destW, destH, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);
        return bm1;
    }

第二种方法效率比第一种快40%左右,第二种不能支持任意角度旋转,但是需要对于需要提高效率的地方,这个方法真管用。

你可能感兴趣的:(Android 图片旋转)