在android下载后图像调整大小

时间:2016-07-02 18:06:18

标签: android

enter image description here我正在使用AsyncTask方法从服务器下载图像。它在下载时以全屏显示图像,但下载完成后,图像在屏幕中央变小。

以下是代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.show_pics);

    DownloadTask downloadTask = new DownloadTask();

    downloadTask.execute("https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg");
}

private Bitmap downloadUrl(String strUrl) throws IOException {
    Bitmap bitmap = null;
    InputStream iStream = null;
    try {
        URL url = new URL(strUrl);
        /** Creating an http connection to communcate with url */
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        /** Connecting to url */
        urlConnection.connect();

        /** Reading data from url */
        iStream = urlConnection.getInputStream();

        /** Creating a bitmap from the stream returned from the url */
        bitmap = BitmapFactory.decodeStream(iStream);

    } catch (Exception e) {
        //Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
    }
    return bitmap;
}

private class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
    Bitmap bitmap = null;

    @Override
    protected Bitmap doInBackground(String... url) {
        try {
            bitmap = downloadUrl(url[0]);
        } catch (Exception e) {
            //Log.d("Background Task",e.toString());
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        /** Getting a reference to ImageView to display the
         * downloaded image
         */
        ImageView iView = (ImageView) findViewById(R.id.TahlilImageView);

        /** Displaying the downloaded image */
        iView.setImageBitmap(result);

        /** Showing a message, on completion of download process */
        Toast.makeText(getBaseContext(), "Image downloaded successfully", Toast.LENGTH_SHORT).show();
    }
}

1 个答案:

答案 0 :(得分:2)

请查看以下有关ImageView.ScaleType

的网址

ScaleType为您提供了将图像边界缩放到ImageView边界的选项。您可以通过声明以下属性来设置XML:

android:scaleType="fitXY"

或者您可以在代码中动态设置它:

iView.setScaleType(ImageView.ScaleType.FIT_XY);

如果您希望图像填充 ImageView的整个空间,您必须选择FIT_XY。一般来说,你有很多选择,你可以使用它们。因此,选择最适合您需求的那个。