美文网首页
ImageView动态设置宽高

ImageView动态设置宽高

作者: 小婷婷tt | 来源:发表于2021-03-08 13:28 被阅读0次

    要求宽高比:宽高640240px
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout1">

            <ImageView
                android:id="@+id/imageView3"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/image032504" />
        </LinearLayout>
    

    int width = ViewUtil.getScreenWidth(context);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, (width - ViewUtil.dp2px(context, 32)) * 240 / 640);
    imageView3.setLayoutParams(params);
    Glide.with(context).load(dataBean.getImages()).into(imageView3);

    用到所需方法:
    private static int mScreenWidth;

    /**
     * 获取手机屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕的宽度
     */
    public static int getScreenWidth(Context context) {
        if (mScreenWidth <= 0) {
            mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
        }
        return mScreenWidth;
    }
    
    /**
     * 将dp值转换为px值
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    相关文章

      网友评论

          本文标题:ImageView动态设置宽高

          本文链接:https://www.haomeiwen.com/subject/zlasrktx.html