【问题标题】:ImageButton LayoutProblem with setImageDrawable带有 setImageDrawable 的 ImageButton LayoutProblem
【发布时间】:2012-12-03 15:14:03
【问题描述】:

我正在尝试在运行时设置 ImageButton 的图像。它应该填满屏幕的宽度,并使用正确缩放所需的高度空间。

ImageButton 声明如下:

    <ImageButton
        android:id="@+id/map_plan_topview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:onClick="onMapImageClicked"
        android:background="#0000"
        android:scaleType="fitXY" />

现在我正在尝试设置图像:

        ImageButton topView = (ImageButton) findViewById(R.id.map_plan_topview);
        Drawable d = Drawable.createFromPath(path);
        topView.setImageDrawable(d);

Images 的宽度使用 fill_parent 进行缩放,但未正确拉伸高度。 如果我使用 topView.setImageResource(R.drawable.button_where_citymap); 相反,一切正常,但我确实想在运行时从文件路径设置源代码。

我做错了什么?

【问题讨论】:

    标签: android android-layout android-button android-image


    【解决方案1】:

    fitXY 在不考虑比例的情况下拉伸图像。如果比例很重要,请使用center_cropcenter_inside

    您也可以在代码中设置ScaleType

    ImageButton topView = (ImageButton) findViewById(R.id.map_plan_topview);
    Drawable d = Drawable.createFromPath(path);
    topView.setScaleType(ScaleType.CENTER_CROP);
    topView.setImageDrawable(d);
    

    【讨论】:

    • 我认为 adjustViewBounds 保持图像的 aspectRatio。但是,当我使用 CENTER_CROP 和 CENTER_INSIDE 尝试它时,它在使用 setImageRessource 时都可以工作,但在我使用 setImageDrawable 时却不一样。 CENTER_CROP 没有向我显示整个图像(尽管它被正确缩放)并且 CENTER_INSIDE 向我显示了整个图像,但没有填充父母的宽度。
    【解决方案2】:

    您应该使用“SetImageResource”代替“setImage Drawable”...!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多