how to rotate a bitmap 90 degrees

后端 未结 10 1573
离开以前
离开以前 2020-11-28 03:09

There is a statement in android canvas.drawBitmap(visiblePage, 0, 0, paint);

When I add canvas.rotate(90), there is no effect. But if I wri

相关标签:
10条回答
  • 2020-11-28 03:34

    Just be careful of Bitmap type from java platform call like from comm1x's and Gnzlt's answers, because it might return null. I think it is also more flexible if the parameter can be any Number and use infix for readability, depends on your coding style.

    infix fun Bitmap.rotate(degrees: Number): Bitmap? {
        return Bitmap.createBitmap(
            this,
            0,
            0,
            width,
            height,
            Matrix().apply { postRotate(degrees.toFloat()) },
            true
        )
    }
    

    How to use?

    bitmap rotate 90
    // or
    bitmap.rotate(90)
    
    0 讨论(0)
  • 2020-11-28 03:37

    If you rotate bitmap, 90 180 270 360 is ok but for other degrees canvas will draw bitmap with different size.

    So,the best way is

    canvas.rotate(degree,rotateCenterPoint.x,rotateCenterPoint.y);  
    canvas.drawBitmap(...);
    canvas.rotate(-degree,rotateCenterPoint.x,rotateCenterPoint.y);//rotate back
    
    0 讨论(0)
  • 2020-11-28 03:39

    Using Java createBitmap() method you can pass the degrees.

    Bitmap bInput /*your input bitmap*/, bOutput;
    float degrees = 45; //rotation degree
    Matrix matrix = new Matrix();
    matrix.setRotate(degrees);
    bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
    
    0 讨论(0)
  • 2020-11-28 03:42
    public static Bitmap RotateBitmap(Bitmap source, float angle)
    {
          Matrix matrix = new Matrix();
          matrix.postRotate(angle);
          return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }
    

    To get Bitmap from resources:

    Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
    
    0 讨论(0)
  • 2020-11-28 03:45

    Short extension for Kotlin

    fun Bitmap.rotate(degrees: Float): Bitmap {
        val matrix = Matrix().apply { postRotate(degrees) }
        return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
    }
    

    And usage:

    val rotatedBitmap = bitmap.rotate(90f)
    
    0 讨论(0)
  • 2020-11-28 03:46

    I would simplify comm1x's Kotlin extension function even more:

    fun Bitmap.rotate(degrees: Float) =
        Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)
    
    0 讨论(0)
提交回复
热议问题