【问题标题】:Android center the Image Inside match_parentAndroid中心的图像里面match_parent
【发布时间】:2019-10-08 09:44:57
【问题描述】:

在 ImageView 中将图像居中,将宽度和高度设置为 match_parent

图像视图

<ImageView
    android:adjustViewBounds="true"
    android:id="@+id/iv_Image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:scaleType="matrix"
    android:src="@drawable/test_image" />

由于使用缩放和触摸事件,scaleType 设置为“矩阵”。

如何将 ImageView 中的图像居中。

【问题讨论】:

    标签: android imageview


    【解决方案1】:

    首先获取设备的宽度和高度

    DisplayMetrics displayMetrics = new DisplayMetrics();
    float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
    float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
    

    使用 image_width 计算 ImageView CenterX

    float imageCenterX = (displayMetrics.widthPixels - image_width) / 2;
    

    使用 image_height 计算 ImageView CenterY

    float imageCenterY = image_height > displayMetrics.heightPixels/2 ? 0 : dpHeight/2
    

    为图像设置新矩阵

    Matrix matrix_ = new Matrix();
    matrix_.postTranslate(imageCenterX, imageCenterY);
    ivImageView.setImageMatrix(matrix_);
    

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多