【问题标题】:Change Image view height and width programmatically based on drawable images根据可绘制图像以编程方式更改图像视图的高度和宽度
【发布时间】:2017-03-20 10:43:44
【问题描述】:

我想根据可绘制的图像大小更改 Imageview 的高度和宽度 以编程方式?我有两种类型的图像,一种是水平的,另一种是垂直的。默认情况下,我已经为垂直图像编写了我的 xml 代码,但我想通过 java 代码更改水平图像的图像视图高度和宽度。如何做到这一点?

我的xml代码是

<RelativeLayout
    android:paddingTop="47dp"
    android:paddingBottom="48dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:id="@+id/flipcardWrapper">

    <ImageView
        android:orientation="horizontal"
        android:layout_width="365dp"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:id="@+id/imgtrans"
        android:background="@android:color/transparent" />

而我改变图像视图高度和宽度的java代码是

imgview = (ImageView) findViewById(R.id.imgtrans);
    Drawable d = getResources().getDrawable(R.drawable.image1);
    int h = d.getIntrinsicHeight();
    int w = d.getIntrinsicWidth();



    if(d.getIntrinsicHeight()==797 && d.getIntrinsicWidth()==1218)
    {
        imgtrans.getLayoutParams().width=300;
        imgtrans.requestLayout();

    }

【问题讨论】:

    标签: android image android-imageview


    【解决方案1】:

    在drawable中设置两个水平的图像,另一个是垂直的。然后根据它设置图像找到屏幕方向

    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
     Drawable d = getResources().getDrawable(R.drawable.imagehorizontal);
    //set your other properties
    }
    
    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
     Drawable d = getResources().getDrawable(R.drawable.imagevertical);
    //set your other properties
    }
    

    【讨论】:

      【解决方案2】:

      在 java 代码中使用 ViewGroup.LayoutParams.MATCH_PARENT。

      imgview = (ImageView) findViewById(R.id.imgtrans);
      Drawable d = getResources().getDrawable(R.drawable.image1);
      int h = d.getIntrinsicHeight();
      int w = d.getIntrinsicWidth();
      
      
      
      if(d.getIntrinsicHeight()==797 && d.getIntrinsicWidth()==1218)
      {
          imgtrans.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
          imgtrans.getLayoutParams().height = someValue;
          imgtrans.requestLayout();
      }
      

      【讨论】:

      • isHori(d) 我在 android 中找不到这个。你能告诉我如何实现这一目标
      • @user7125006 对不起,我的英文太差了,表达不清楚。所以我修改了答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多