Android 根据textivew';将图片调整为;s码
我有一个Android 根据textivew';将图片调整为;s码,android,android-image,Android,Android Image,我有一个TextView,因为我正在drawableLeft <TextView android:id="@+id/imgChooseImage" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="3" android:background="@drawable/slim_spinner_normal" android:drawabl
TextView
,因为我正在drawableLeft
<TextView
android:id="@+id/imgChooseImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:background="@drawable/slim_spinner_normal"
android:drawableLeft="@drawable/ic_launcher"/>
下面是java代码
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// If set to true, the decoder will return null (no bitmap), but
// the out... fields will still be set, allowing the caller to
// query the bitmap without having to allocate the memory for
// its pixels.
bmOptions.inJustDecodeBounds = true;
int photoW = hListView.getWidth();
int photoH = hListView.getHeight();
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / 100, photoH / 100);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), Const.template[arg2],bmOptions);
Drawable draw = new BitmapDrawable(getResources(), bitmap);
/* place image to textview */
TextView txtView = (TextView) findViewById(R.id.imgChooseImage);
txtView.setCompoundDrawablesWithIntrinsicBounds(draw, null,null, null);
position = arg2;
您需要一种方法来计算布局后
TextView
的确切高度,以便可以调整drawableLeft
属性的位图大小。
有几个问题使问题更加复杂:
scaleFactor
时要考虑到这一点scaleFactor
没有提供精确大小的图像请求。
它仅将位图的大小限制为尽可能小的图像
这仍然是相同的或大于您的请求,以便保存
记忆。您仍然需要将图像调整到精确的高度
你已经计算过了drawableLeft
方法无法克服上述问题,我认为有一种更好的方法可以实现预期的布局,而无需使用Java代码调整大小
我认为您应该将TextView替换为水平方向的线性布局
,其中包含图像视图
和文本视图
。将文本视图的高度设置为“WRAP\u CONTENT”
,并将ImageView的scaleType设置为“center”,如下所示:
android:scaleType="center"
LinearLayout将具有TextView中文本的高度,ImageView的缩放类型将强制位图在布局期间自动调整大小。这里提供了可用scaleType的参考:
当然,您必须调整LinearLayout、ImageView和TextView的XML布局参数,以便它们以您想要的方式居中、对齐和定向。但是,至少你只需要做一次
由于您似乎将从应用程序资源将照片加载到ImageView中,您可能知道图像不是很大,因此您可以直接打开位图,或使用inSampleSize=scaleFactor=1
。否则,如果图像特别大或出现OutOfMemoryError
异常,则按如下方式计算scaleFactor
:
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}