在我的应用程序中,我有一个活动将图像加载到位于屏幕中心的ImageView中。首先缩放图像以适合屏幕,然后在设置ImageView的位图之后,将ImageView的大小调整为与位图相同的大小。
ImageView imageView = (ImageView) galleryActivity.findViewById(R.id.selectedImage);
Bitmap image = fileList.get(displayedImageIndex).loadScaledImage();
imageView.setImageBitmap(image);
imageView.getLayoutParams().width = image.getWidth();
imageView.getLayoutParams().height = image.getHeight();
imageView.requestLayout();
问题是,在调整ImageView大小后,它不再位于屏幕中间的中心,而是与其父级的顶部对齐。我尝试了imageView.setY和imageView.setTranslationY来尝试将其移回中心,但这些都没有重新定位View。有没有办法让ImageView在调整大小后保持在父级中心对齐?
这是布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/AppTheme"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/selectedImage"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleActionBar" />
</RelativeLayout>
答案 0 :(得分:1)
ImageView imageView = (ImageView)
galleryActivity.findViewById(R.id.selectedImage);
Bitmap image = fileList.get(displayedImageIndex).loadScaledImage();
imageView.setImageBitmap(image);
int cxScreen; // you must fill it
int cyScreen; // this to
int cxImg = imageView.getWidth(); // change image to imageView
int cyImg = imageView.getHeight(); // as up
LayoutParams lp = new LayoutParams(cxImg, cyImg);
lp.leftMargin = (cxScreen-cxImg)/2;
lp.topMargin = (cyScreen-cyImg)/2; // change something to cyScreen
imageView.setLayoutParams(lp);
编辑更改3行
Log.i("TAG", "cxS:"+cxScreen.toString()+", cyS:"+cyScreen.toString());
Log.i("TAG", "image:"+imageView.toString());
Log.i("TAG", "parent:"+(imageView.getParent()).toString());
答案 1 :(得分:-1)
试试这个:
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);