【问题标题】:Repositioning ImageView Programmatically Android以编程方式重新定位 ImageView Android
【发布时间】:2016-02-12 12:47:58
【问题描述】:

在我的应用程序中,我有一个将图像加载到位于屏幕中心的 ImageView 的活动。图片先缩放到适合屏幕大小,然后在ImageView的bitmap设置好后,ImageView再resize到和Bitmap一样的大小。

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 来尝试将其移回中心,但它们都没有重新定位视图。有什么办法可以让 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>

【问题讨论】:

  • 发布您的布局。你绝对可以让它居中,但你如何使用它会改变最好的方式。但它可能是你想要的重力或 layout_gravity。

标签: android bitmap android-imageview


【解决方案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);

EDIT改3行

Log.i("TAG", "cxS:"+cxScreen.toString()+", cyS:"+cyScreen.toString());
Log.i("TAG", "image:"+imageView.toString());
Log.i("TAG", "parent:"+(imageView.getParent()).toString());

【讨论】:

  • 这可行,但有点复杂。在布局中设置重力要容易得多。
  • 最简单的解决方案,与布局和重力无关
  • 不,不是。你做了很多计算,你有两个部分你甚至不知道如何填写。或者你可以在布局中设置正确的重力,做0次计算。
  • 在这个灵活的解决方案中,图像可以动态移动到屏幕上的每个位置,在本例中为中心。
  • @skippy 我试过这个解决方案,但它不起作用,它将 ImageView 的中心对齐到屏幕的右上角
【解决方案2】:

试试这个:

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

【讨论】:

  • 这会将位图裁剪为居中,但不会调整宽度和高度
猜你喜欢
  • 1970-01-01
  • 2016-06-24
  • 2019-10-09
  • 1970-01-01
  • 2020-10-06
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多