3.Android基础:常见控件----->ImageView

来源:互联网 发布:渊默而雷声知乎 编辑:程序博客网 时间:2024/05/17 06:44

ImageView控件是用于显示图片


1.重要的属性

android:src

用于指定显示图片的路径,图片一般放在res/drawable目录下


2.重要的方法

1.setImageResource方法

功能:设置ImageView将显示的图片

参数:图片资源为ID,如R.drawable.hq

2.setImageBitmap方法

功能:设置ImageView将显示的图片

参数:位图对象


下面简单演示下

这个xml布局文件

<LinearLayout 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=".MainActivity"     android:orientation="vertical">    <!-- 直接引用图片 -->     <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:src="@drawable/ic_launcher"        />         <!-- setImageResource方法 -->    <ImageView        android:id="@+id/imageView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         />                  <!-- setImageBitmap方法 -->      <ImageView        android:id="@+id/imageView3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         /></LinearLayout>

这个是测试类

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);click2();click3();}//xml设置srcpublic void click1() {ImageView imageview = (ImageView) findViewById(R.id.imageView1);}public void click2() {ImageView imageview = (ImageView) findViewById(R.id.imageView2);imageview.setImageResource(R.drawable.ic_launcher);}//位图显示public void click3() {//从资源文件获得Bitmap对象Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);//获取图片宽高int screenWidth = pic.getWidth();int screenHeight = pic.getHeight();//缩放图片//获取缩放后的图片像素信息Bitmap scaled = Bitmap.createScaledBitmap(pic, 200, 200 * screenHeight / screenWidth, false);//获取imageView3控件对象ImageView image = (ImageView) findViewById(R.id.imageView3);//显示缩放比例image.setImageBitmap(scaled);}}


0 0
原创粉丝点击