Scaling ImageView to device width

前端 未结 9 898
清酒与你
清酒与你 2020-12-05 00:54

In my Android App I have a Activity which show images which have following size 244 x 330. I want to show those images in full device width.

My layout f

9条回答
  •  情歌与酒
    2020-12-05 01:39

    manage to achieve what I wanted, which hopefully is the same as your aim:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pgviewer);
    
        ImageView PgContainer = (ImageView)findViewById(R.id.imageView1);
    
        String Page = String.valueOf(getIntent().getExtras().getInt("Page"));
        try {
            PgContainer.setImageBitmap(getBitmapFromAsset(Page));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        PgContainer.setScaleType(ScaleType.FIT_CENTER);
        PgContainer.scrollTo(0, 0);
        PgContainer.setScrollBarStyle(0);
    }
    

    then to scale the bitmap:

    private Bitmap getBitmapFromAsset(String strName) throws IOException
    {
        AssetManager assetManager = getAssets();
        InputStream istr = assetManager.open(strName+".png");
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
    
        float screenWidth = getResources().getDisplayMetrics().widthPixels;
        int ih=bitmap.getHeight();
        int iw=bitmap.getWidth();
        float scalefactor = screenWidth/iw;
        //w = 480, h=~
        //int newh = bitmap.getHeight()/bitmap.getWidth();
        return android.graphics.Bitmap.createScaledBitmap(bitmap, (int)(iw*scalefactor), (int)(ih*scalefactor), true);
        //return bitmap;
    }
    

提交回复
热议问题