歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android UI之ImageView圖片視圖

Android UI之ImageView圖片視圖

日期:2017/3/1 10:47:06   编辑:Linux編程

ImageView是一個顯示圖片的組件,用一個例子介紹該組件的簡單運用:

在樣式文件中:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <!-- android:src設置ImageView所顯示的Drawable對象的ID -->
  7. <ImageView
  8. android:id="@+id/img1"
  9. android:layout_width="fill_parent"
  10. android:layout_height="300dp"
  11. android:background="#cccccc"
  12. android:src="@drawable/pig" />
  13. <!--android:scaleType設置所顯示的圖片如何縮放或移動以適應ImageView的大小 其值在中文API上有詳細的說明 -->
  14. <ImageView
  15. android:id="@+id/img2"
  16. android:layout_width="100dp"
  17. android:layout_height="100dp"
  18. android:background="#cccccc"
  19. android:scaleType="fitStart"
  20. android:layout_marginTop="20dp"
  21. />
  22. </LinearLayout>

該樣式文件中有兩個ImageView組件,第一個用來顯示我們想要展示的圖片,第二ImageView用來顯示當點擊圖片上某一位置時在該組件上顯示部分圖片,代碼實現該功能:

  1. package cn.class3g.activity;
  2. import android.app.Activity;
  3. import android.graphics.Bitmap;
  4. import android.graphics.drawable.BitmapDrawable;
  5. import android.os.Bundle;
  6. import android.view.MotionEvent;
  7. import android.view.View;
  8. import android.view.View.OnTouchListener;
  9. import android.widget.ImageView;
  10. public class ImageViewDemo extends Activity implements OnTouchListener {
  11. ImageView imageView1, imageView2;
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. this.setContentView(R.layout.imageview_layout);
  15. findViews();
  16. }
  17. private void findViews() {
  18. imageView1 = (ImageView) findViewById(R.id.img1);
  19. imageView2 = (ImageView) findViewById(R.id.img2);
  20. //為imageView添加觸摸監聽事件
  21. imageView1.setOnTouchListener(this);
  22. }
  23. public boolean onTouch(View v, MotionEvent event) {
  24. float scale = 412 / 320;
  25. //獲取需要顯示的圖片的開始點
  26. int x = (int) (event.getX() * scale);
  27. int y = (int) (event.getY() * scale);
  28. //需要考慮邊界問題
  29. int width = (int) (100 * scale);
  30. int height = (int) (100 * scale);
  31. //獲取圖片顯示框中的位圖
  32. BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView1.getDrawable();
  33. //顯示圖片指定的區域
  34. imageView2.setImageBitmap(Bitmap.createBitmap(bitmapDrawable.getBitmap(),
  35. x,y, width, height));
  36. return false;
  37. }
  38. }

在模擬器上的效果為

Copyright © Linux教程網 All Rights Reserved