美文网首页
AvatarView 自定义圆形 View

AvatarView 自定义圆形 View

作者: dcme | 来源:发表于2016-07-29 23:48 被阅读0次

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"/>

AvatarView 代码

相关文章

网友评论

      本文标题:AvatarView 自定义圆形 View

      本文链接:https://www.haomeiwen.com/subject/cznzjttx.html