Android UI之ImageView图片视图

Linux大全评论432 views阅读模式

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.   
  23. </LinearLayout>  
  1. package cn.class3g.activity;  
  2.   
  3. import android.app.Activity;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.drawable.BitmapDrawable;  
  6. import android.os.Bundle;  
  7. import android.view.MotionEvent;  
  8. import android.view.View;  
  9. import android.view.View.OnTouchListener;  
  10. import android.widget.ImageView;  
  11.   
  12. public class ImageViewDemo extends Activity implements OnTouchListener {  
  13.     ImageView imageView1, imageView2;  
  14.   
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         this.setContentView(R.layout.imageview_layout);  
  18.         findViews();  
  19.     }  
  20.   
  21.     private void findViews() {  
  22.         imageView1 = (ImageView) findViewById(R.id.img1);  
  23.         imageView2 = (ImageView) findViewById(R.id.img2);  
  24.         //为imageView添加触摸监听事件  
  25.         imageView1.setOnTouchListener(this);  
  26.     }  
  27.   
  28.     public boolean onTouch(View v, MotionEvent event) {  
  29.         float scale = 412 / 320;  
  30.         //获取需要显示的图片的开始点  
  31.         int x = (int) (event.getX() * scale);  
  32.         int y = (int) (event.getY() * scale);  
  33.           
  34.         //需要考虑边界问题  
  35.         int width = (int) (100 * scale);  
  36.         int height = (int) (100 * scale);  
  37.         //获取图片显示框中的位图  
  38.         BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView1.getDrawable();  
  39.         //显示图片指定的区域  
  40.         imageView2.setImageBitmap(Bitmap.createBitmap(bitmapDrawable.getBitmap(),  
  41.                 x,y, width, height));  
  42.           
  43.         return false;  
  44.     }  
  45. }  

Android UI之ImageView图片视图

企鹅博客
  • 本文由 发表于 2019年9月12日 23:22:53
  • 转载请务必保留本文链接:https://www.qieseo.com/173059.html

发表评论