【发布时间】:2014-12-11 18:37:08
【问题描述】:
我正在创建一个从 url 下载图像的应用程序,将它们保存在设备上,然后必须将它们加载到具有固定大小的 ImageView 中。 对于文件的下载和保存,我没有问题,但是当我尝试在 ImageView 中设置图像时出现致命错误,因为图像对于我的 ImageView 来说太大(我认为......)。
这是xml文件:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff9f9f"
android:layout_margin="2dip"
android:padding="2dip">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff9f9f"
android:layout_margin="2dip"
android:padding="2dip">
<TextView
android:id="@+id/notizieTitolo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/immagineNotizie"
android:text="Titolo"
android:textColor="#6b71f1"
android:textSize="20dip"
android:layout_margin="2dip" />
<TextView
android:id="@+id/notizieSottoTitolo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/immagineNotizie"
android:text="SottoTitolo"
android:textSize="15dip"
android:layout_margin="2dip"/>
<ImageView
android:background="@drawable/icona"
android:id="@+id/immagineNotizie"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_margin="2dip" />
</RelativeLayout>
</ScrollView>
是一个简单的布局,一个ImageView,ImageView右边一个TextView,all下面一个TextView
重要的是 ImageView 和高度。设置为 100dip(如果我将 2dip 算作边距)。
图像保存在位图中的类的代码。
public class Notizia {
String url;
String titolo;
String sottoTitolo;
String nomeImmaginSalvata;
Bitmap immagine;
public Notizia(String tit, String sottoTit, Bitmap imm, String lk){
titolo = tit;
sottoTitolo = sottoTit;
immagine = imm;
url = lk;
nomeImmaginSalvata = nomeImmSalvata;
}
}
在这种情况下,我将在下载后立即使用图像,而不将其保存到磁盘,因为保存不是必需的。
这是使用 xml 布局创建动态布局的代码
LayoutInflater layoutInflator = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout insertPoint = (LinearLayout) findViewById(R.id.ll_content);
List views = new ArrayList();
Iterator<Notizia> it = (Dati.listaNotizie).iterator();
while (it.hasNext()){
Notizia not = it.next();
View view = layoutInflator.inflate(R.layout.layout_notizie, null);
TextView textView = (TextView) view.findViewById(R.id.notizieTitolo);
Bitmap yourBitmap = not.getImmagine();
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, 10, 10, true);
TextView textView1 = (TextView) view.findViewById(R.id.notizieSottoTitolo);
ImageView img = (ImageView) findViewById(R.id.immagineNotizie);
img.setImageBitmap(resized);
textView.setText(not.getTitolo());
textView1.setText(not.getSottoTitolo());
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
views.add(view);
}
for(int i = 0; i<views.size(); i++)
insertPoint.addView((View) views.get(i));
}
我的问题是:如何将图像宽度和高度调整为 100dip(或 98)?
我试过了
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, width, heigh, true);
但什么都没有。
【问题讨论】:
标签: android image bitmap resize