【问题标题】:Programmatically setting ImageView caused distortion以编程方式设置 ImageView 导致失真
【发布时间】:2018-03-04 07:56:09
【问题描述】:

我正在将ImageView 设置为从远程服务器下载的文件,然后保存到设备的本地存储中。由于某种原因,图像变得扭曲。根据我的研究,如果我设置了ImageViewscaleTypeadjustViewBoundsmaxWidthmaxHeight 属性,那么Android 将为我缩放图像。这看起来很奇怪,因为在我的其他非 Android 开发中,我总是必须先以编程方式调整图像大小,然后再显示它。但是,this post 表示 Android 会这样做。

这是我要显示的图像:Image

扭曲的图像:

代码:

    <ImageView
        android:id="@+id/title_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxWidth="60dp"
        android:maxHeight="60dp"
        android:scaleType="fitCenter"
        android:adjustViewBounds="true"
        />

    String path =  getExternalStorageDirectory() + "/MyApp/Images";
    String fileName = "Test.jpg";
    File imageFile = new File(path, fileName);

    if (imageFile.exists())
    {
        Uri imageUri = Uri.fromFile(imageFile);
        ((ImageView)findViewById(R.id.title_image)).setImageURI(thumbnail);
    }

【问题讨论】:

    标签: android android-imageview image-scaling


    【解决方案1】:

    如果它对任何人有帮助,我最终会使用以下代码调整图像大小:

                final URLConnection ucon = new URL(url).openConnection();
                final InputStream is = ucon.getInputStream();
                final Bitmap b = BitmapFactory.decodeStream(is);
    
                int origWidth = b.getWidth();
                int origHeight = b.getHeight();
                float scaleWidth = ((float) width) / origWidth;
                float scaleHeight = ((float) width) / origHeight;
    
                final Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
    
                Bitmap b2 = Bitmap.createBitmap(b, 0, 0, origWidth, origHeight, matrix, false);
    
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                b2.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(outStream.toByteArray());
                fo.flush();
                fo.close();
                outStream.flush();
                outStream.close();
                b.recycle();
                b2.recycle();
    

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2012-09-03
      • 1970-01-01
      • 2018-04-15
      • 2020-07-01
      • 2014-10-05
      相关资源
      最近更新 更多