Android:以编程方式更改ImageView的位置和大小

时间:2014-03-13 10:31:44

标签: android imageview

我在LinearLayout中有一个ImageView。要更改此ImageView的位置,我使用的是MarginLayoutParams类。以下是代码。

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@drawable/sample_frame" >

<ImageView
    android:id="@+id/frame1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/box" />

</LinearLayout>

填充代码

MarginLayoutParams mlp = (MarginLayoutParams) frame1.getLayoutParams();
mlp.setMargins(actualFrameX1, actualFrameY1, 0, 0);//all in pixels
frame1.setLayoutParams(mlp);

actualFrameX1是左边距 actualFrameY1是最高保证金 frame1是IMageView

到这里一切都很好但是当我设置&#34; mlp&#34;的宽度和高度时,边距会改变。 如果宽度和高度相同,比如100px和100px,那么它很好但如果宽度和高度不同,比如85px和100px,则边距会发生变化。

MarginLayoutParams mlp = (MarginLayoutParams) frame1.getLayoutParams();
mlp.setMargins(actualFrameX1, actualFrameY1, 0, 0);//all in pixels
mlp.width = 85;
mlp.height = 100;
frame1.setLayoutParams(mlp);

以下是两个截图 - 绿色框的左上角应与白色框的左上角匹配

屏幕截图1 - 宽度和高度相同(100和100)

屏幕截图2 - 宽度和高度不同(85和100)

Screenshot 1

Screenshot 2

当我设置mpl.width = 85和mpl.height = 100时,图像的填充会像屏幕截图2中那样改变。但是如果宽度和高度相同,那么填充就像在屏幕截图中一样。为什么paddings会改变?请帮帮我。

0 个答案:

没有答案
相关问题