user465001
user465001

Reputation: 846

Aspect ratio is off when scaling down and drawing a bitmap

The image I am using is from a 4x6. So the aspect ratio should be about .66. When I calculate the aspect ration in my code , I get around .66. However, the height of the displayed image looks squashed. The image only looks right if I set the aspect ratio manually to around .85.

Since setting the aspect ratio manually is not perfect, how can I get the can I keep the height of my image from appearing to be squashed.

public class SpotGameActivity extends Activity {

private Bitmap mBitmap;

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
    setContentView(new BitMapView(this, mBitmap));

}

    class BitMapView extends View {
        Bitmap mBitmap = null;

        public BitMapView(Context context, Bitmap bm) {
            super(context);
            mBitmap = bm;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            // called when view is drawn
            Paint paint = new Paint();
            paint.setFilterBitmap(true);
            // The image will be scaled so it will fill the width, and the
            // height will preserve the image’s aspect ration
            float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
            Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getHeight() * aspectRatio));

            String AR = Double.toString(aspectRatio);

            //Rect dest = new Rect(0, 0, getWidth(), getHeight());

            canvas.drawBitmap(mBitmap, null, dest, paint);
            Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();   
        }
    }

}

Upvotes: 0

Views: 801

Answers (1)

Shubhayu
Shubhayu

Reputation: 13552

Aspect = width/height

newHeight = newWidth/Aspect

Do this,

Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));

Upvotes: 3

Related Questions