目录
图像视图ImageView
图像视图展示的图片通常位于res/drawable***目录,设置图像视图的显示图片有两种方式:
1、在XML文件中,通过属性android:src设置图片资源,属性值格式形如“@drawable/不含扩展名的图片名称”。
2、在Java代码中,调用setImageResource方法设置图片资源,方法参数格式形如“R.drawable.不含扩展名的图片名称”。
方式一:
<?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">
<ImageView
android:id="@+id/iv_scale"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_marginTop="5dp"
android:src="@drawable/apple.png"/>
</LinearLayout>
方式二:
package com.example.myapplication3;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageScaleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_scale);
ImageView iv_scale=findViewById(R.id.iv_scale);
iv_scale.setImageResource(R.drawable.apple);
}
}
图像视图的缩放类型
ImageView本身默认图片居中显示,若要改变图片的显示方式,可通过scaleType属性设定,该属性的取值说明如下:
和控件宽高保持一致了
保持宽高比例,位于视图上方或左侧
系统的默认值是fitCenter
方式二:若在代码中
package com.example.myapplication3;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageScaleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_scale);
ImageView iv_scale=findViewById(R.id.iv_scale);
iv_scale.setImageResource(R.drawable.apple);
iv_scale.setScaleType(ImageView.ScaleType.CENTER);
}
}
图像按钮ImageButton
ImageButton是显示图片的图像按钮,但它继承自ImageView,而非继承Button。
ImageButton和Button之间的区别有:
1、Button即可显示文本也可显示图片,ImageButton只能显示图片不能显示文本。
2、ImageButton上的图像可按比例缩放,而Button通过背景设置的图片会拉伸变形。
3、Button只能靠背景显示一张图片,而ImageButton可分别在前景和背景显示图片,从而实现两种图片叠加的效果。
ImageButton的使用场景
<?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">
<ImageButton
android:layout_width="match_parent"
android:layout_height="80dp"
android:src="@drawable/apple"
android:scaleType="fitCenter"/>
</LinearLayout>
同时展示文本与图像
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图标在左"
android:drawableLeft="@drawable/icon"
android:background="#FFFFFF"
android:drawablePadding="5dp"/>
</LinearLayout>
增加一个Bridge 为了更改图片的背景颜色
实战项目-计算机(典例)