AvatarView 继承 ImageView
public class AvatarView extends ImageView
自定义属性 avatar 表示资源 Id
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="AvatarView">
<attr name="avatar" format="reference"/>
</declare-styleable>
</resources>
Android 5.0 以上版本用 Outline 实现圆形效果
@SuppressLint("NewApi")
private void setAvatarPostLollipop(int avatarDrawableId) {
setClipToOutline(true);
setImageResource(avatarDrawableId);
}
在 onSizeChanged
中构造圆形 Outline
@SuppressLint("NewApi")
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
final int size = Math.min(w, h);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, size, size);
}
});
}
}
Android 5.0 以下使用 RoundedBitmapDrawable 实现圆形效果
private void setAvatarPreLollipop(int avatarDrawableId) {
Drawable drawable = ResourcesCompat.getDrawable(getResources(), avatarDrawableId,
getContext().getTheme());
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
@SuppressWarnings("ConstantConditions")
RoundedBitmapDrawable roundedBitmapDrawable =
RoundedBitmapDrawableFactory.create(getResources(), bitmapDrawable.getBitmap());
roundedBitmapDrawable.setCircular(true);
setImageDrawable(roundedBitmapDrawable);
}
XML 布局中添加 AvatarView
<xyz.caoshen.android.yui.view.AvatarView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:scaleType="centerCrop"
app:avatar="@drawable/avatar"/>