AvatarView 自定义圆形 View

AvatarView 继承 ImageView

public class AvatarView extends ImageView

自定义属性 avatar 表示资源 Id


    
            
            
    

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

    

AvatarView 代码

你可能感兴趣的:(AvatarView 自定义圆形 View)