Search code examples
androidbitmapscale

Scale Bitmap using drawBitmap


Basically I have 640 x 480 image and I want to scale and draw it using drawBitmap. For simplicity lets just say I have 854 x 480 android screen. Here is my code

MainActivity.java

public class MainActivity extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(new MainLayout(this));
  }
}
class MainLayout extends RelativeLayout
{
  public MainLayout(Context context)
  {
    super(context);
    setWillNotDraw(false);
  }
  @Override
  public void onDraw(Canvas canvas)
  {
    super.onDraw(canvas);
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
    bitmap = Bitmap.createScaledBitmap(bitmap, 854, 480, true);
    canvas.drawBitmap
    (
      bitmap,
      null,
      new Rect(0, 0, 854, 480),
      null
    );
  }
}

The result is different than what I want. Any suggestion?


Solution

  • use this

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    
    canvas.drawBitmap(bitmap, x, y, paint);