Java 将ImageView高度设置为该高度的50%';s宽度
我想将ImageView高度设置为宽度的50%。 我怎么能做到? 例如,如果ImageView的宽度等于200dp,我想这是高度等于100dp 我试过了,但没用Java 将ImageView高度设置为该高度的50%';s宽度,java,android,imageview,Java,Android,Imageview,我想将ImageView高度设置为宽度的50%。 我怎么能做到? 例如,如果ImageView的宽度等于200dp,我想这是高度等于100dp 我试过了,但没用 int img_width = cover_img.getLayoutParams().width; int img_height = img_width/2; cover_img.getLayoutParams().width = img_width; cover_img.getLayo
int img_width = cover_img.getLayoutParams().width;
int img_height = img_width/2;
cover_img.getLayoutParams().width = img_width;
cover_img.getLayoutParams().height = img_height;
cover_img.requestLayout();
请帮帮我
更新:
我写了一篇文章,我用这个类来做这件事,这是一个简单、简单、快速的方法,可以将ImageView的高度设置为宽度的50%
public class RectImage extends ImageView
{
public RectImage(Context context)
{
super(context);
}
public RectImage(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public RectImage(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
public RectImage(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, widthSize/2);
}
}
试试下面给出的方法
int img_width = cover_img.getDrawable().getIntrinsicWidth();
int img_height = img_width/2;
cover_img.getLayoutParams().width = img_width;
cover_img.getLayoutParams().height = img_height;
cover_img.requestLayout();
如果使用
ConstraintLayout
作为根,则可以执行以下操作:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:animateLayoutChanges="true"
>
<ImageView
android:id="@+id/image_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
app:layout_constraintDimensionRatio="1:0.50"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
它主要围绕着layout\u constraintDimensionRatio
这将自动实现您想要的,可能也是最简单的
当然,请随意定位视图,忽略此处的约束准则,我只是将它们放在那里作为一个完整的示例。如果使用“约束布局”,您可以在xml中设置比率
视图大小在onDraw阶段之后定义。你在哪里试过你的代码?我在我的活动中试过。但是在哪种方法中?onCreate/onResume/…?onCreate方法
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/cover_img"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="2:1" />
</androidx.constraintlayout.widget.ConstraintLayout>
//Your layout param type
ViewGroup.LayoutParams lpm = cover_img.getLayoutParams();
int width = lpm.width;
int height =width/2;
lpm.height = height;
cover_img.setLayoutParams(lpm);
cover_img.requestLayout();