Resizing bitmap is cropping instead of scaling in View

我只是一个虾纸丫 提交于 2019-12-13 19:02:57

问题


I can't figure out how to resize a bitmap. Based on posts here Bitmap.createScaledBitmap is the way to do it but it just doesn't work for me. Because of the nature of the view I'm doing everything in onDraw so I don't think I can use a layout or ImageView. Here's what I'm doing:

I have an image of the Empire State Building that's 200x200. I run this code to set it up:

    private void setupBitmap() {

        int bitmapSize = 100;

        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.empirestate_sm);
        myBitmap = Bitmap.createScaledBitmap(originalBitmap, bitmapSize, bitmapSize, true);
    }

This is is my onDraw:

    protected void onDraw(Canvas canvas) {
         canvas.drawBitmap(myBitmap, 0, 0, null);
    }

And here is the result, note the image is just cropped and not resized:

Just for s&g's if I set the bitmapSize = 200 it looks like this:


回答1:


Ok I've figured it out. What worked for me is leaving the bitmap as is when you create it. Then when you draw it on the canvas set it to the right size. I'm assuming the createScaledBitmap function is broken??

   myCanvas.drawBitmap (landmarkImg, null, new RectF((float)0,(float)0,newWidth,newHeight),null);



回答2:


You can try using an ImageView:

ImageView iv = (ImageView) findViewById(R.id.imageview);

Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.empirestate_sm);
myBitmap = Bitmap.createScaledBitmap(originalBitmap, bitmapSize, bitmapSize, true);

iv.setImageBitmap(myBitmap);


来源:https://stackoverflow.com/questions/22965549/resizing-bitmap-is-cropping-instead-of-scaling-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!