Search code examples
androidbitmapscaleangle

Scale a Bitmap in function of the angle in Android


I want to draw arrow in ellipse shape, almost like here, but I'd like to scale the arrow in function of the angle: reduce the arrow when the radius is low, and increase it when the ratius is big.

The code is:

    for (int i = 0; i < elements.length; i++) {

            int centerX = (viewBitmapWidth / 2) - (bitmap.getWidth() / 2);
            int centerY = (viewBitmapHeight / 2) - (bitmap.getHeight());

            matrix.reset();


    double angle = Math.atan2(
        radiusx * Math.sin(2 * Math.PI * i / elements.length),
        radiusy * Math.cos(2 * Math.PI * i / elements.length));

    matrix.postRotate((float) (angle * 180 / Math.PI),
        (float) (bitmap.getWidth() / 2 + 5 * Math.sin(angle)),
        (float) (bitmap.getHeight() + 5 * Math.cos(angle)));

    matrix.postTranslate(centerX, centerY);

    Bitmap tempBitmap = Bitmap.createScaledBitmap(bitmap,
        bitmap.getWidth(), (int) (bitmap.getHeight() * Math.sin(angle)), false);

    canvas.drawBitmap(tempBitmap, matrix, null);` 

but I obtain this error:

08-29 22:10:29.993: E/AndroidRuntime(1053): java.lang.IllegalArgumentException: width and height must be > 0 08-29 22:10:29.993: E/AndroidRuntime(1053): at android.graphics.Bitmap.createBitmap(Bitmap.java:638) 08-29 22:10:29.993: E/AndroidRuntime(1053): at android.graphics.Bitmap.createBitmap(Bitmap.java:586) 08-29 22:10:29.993: E/AndroidRuntime(1053): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:466) 08-29 22:10:29.993: E/AndroidRuntime(1053): at com.turvy.organicreaction.views.CircleView.onDraw(CircleView.java:156) 08-29 22:10:29.993: E/AndroidRuntime(1053): at android.view.View.draw(View.java:13458)ivityThread.java:4745) ...

I've also tried the postScale or preScale methods of the matrix, but it was'nt good, it changed everything, even the position.

Could you help me with my problem, please? Thanks


Solution

  • The exception says that you're creating a Bitmap with height or width < 0. So use the following to create the Bitmap:

    Bitmap tempBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), 
        (int) (bitmap.getHeight() * Math.abs(Math.sin(angle))), false);