Android代碼中動態設置圖片的大小(自動縮放),位置


項目中需要用到在代碼中動態調整圖片的位置和設置圖片大小,能自動縮放圖片,用ImageView控件,具體做法如下:

1、布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >
    <ImageView
        android:id="@+id/image01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/aabb" />
</RelativeLayout>

2、java代碼

public class MainActivity extends Activity {
	private ImageView image;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		image = (ImageView)findViewById(R.id.image01);        
        //設置圖片的位置
		MarginLayoutParams margin9 = new MarginLayoutParams(
				image.getLayoutParams());
		margin9.setMargins(400, 10, 0, 0);//在左邊距400像素,頂邊距10像素的位置顯示圖片
		RelativeLayout.LayoutParams layoutParams9 = new RelativeLayout.LayoutParams(margin9);
		layoutParams9.height = 600;//設置圖片的高度
		layoutParams9.width = 800; //設置圖片的寬度
		image.setLayoutParams(layoutParams9);
	}
}

  

3、效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM