一. 继承图

二. Xml 中常用的方法

1
2
3
4
android:src="@drawable/图片名"           //设置前景图片或者颜色
android:background="@color/colorAccent" //设置背景图片或者颜色
android:scaleType="fitXY" //拉伸方式
android:adjustViewBounds="true" //使ImageView和图片有一样的长宽比例

三. Java代码常用的方法

1
2
3
4
5
6
7
8
9
public void setImageBitmap(Bitmap bm)                    //设置前景图片

public void setImageResource(@DrawableRes int resId) //设置前景图片

public void setBackgroundColor(@ColorInt int color) //设置背景颜色

public void setBackgroundResource(@DrawableRes int resid)//设置背景图片


四. 常见的问题

问题1:ImageView中src和background的区别以及adjustViewBounds

问题2:ImageView设置背景图片报错:Error inflating class ImageView?

res目录下除了drawable文件夹、还有drawable-v24文件夹,将图片资源从
drawable-v24文件夹移动到drawable文件夹。

问题3:圆角ImageView的实现

参考文章:关于Android圆角ImageView的几种实现方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class XLImageView extends androidx.appcompat.widget.AppCompatImageView {

public XLImageView(Context context) {
super(context);
}

public XLImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public void draw(Canvas canvas) {
//裁剪画布
Path path = new Path();
path.addCircle(getPivotX(),getPivotY(), getWidth() >> 1, Path.Direction.CW);
canvas.clipPath(path);

//绘制
super.draw(canvas);
}
}

参考文章

Android控件之ImageView(一)