Android UI之ImageView图片视图

ImageView是一个显示图片的组件,用一个例子介绍该组件的简单运用:

在样式文件中:

<?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="vertical" >
    <!-- android:src设置ImageView所显示的Drawable对象的ID -->
    <ImageView
        android:id="@+id/img1"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:background="#cccccc"
        android:src="@drawable/pig" />
    <!--android:scaleType设置所显示的图片如何缩放或移动以适应ImageView的大小  其值在中文API上有详细的说明 -->
    <ImageView
        android:id="@+id/img2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#cccccc"
        android:scaleType="fitStart"
        android:layout_marginTop="20dp"
        />

</LinearLayout>

该样式文件中有两个ImageView组件,第一个用来显示我们想要展示的图片,第二ImageView用来显示当点击图片上某一位置时在该组件上显示部分图片,代码实现该功能:


package cn.class3g.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class ImageViewDemo extends Activity implements OnTouchListener {
	ImageView imageView1, imageView2;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.imageview_layout);
		findViews();
	}

	private void findViews() {
		imageView1 = (ImageView) findViewById(R.id.img1);
		imageView2 = (ImageView) findViewById(R.id.img2);
		//为imageView添加触摸监听事件
		imageView1.setOnTouchListener(this);
	}

	public boolean onTouch(View v, MotionEvent event) {
		float scale = 412 / 320;
		//获取需要显示的图片的开始点
		int x = (int) (event.getX() * scale);
		int y = (int) (event.getY() * scale);
		
		//需要考虑边界问题
		int width = (int) (100 * scale);
		int height = (int) (100 * scale);
		//获取图片显示框中的位图
		BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView1.getDrawable();
		//显示图片指定的区域
		imageView2.setImageBitmap(Bitmap.createBitmap(bitmapDrawable.getBitmap(),
				x,y, width, height));
		
		return false;
	}
}

在模拟器上的效果为


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值