Android 仿微信聊天气泡

        第一次写博客,遇见了这样的需求,当时看见那个角就有点触了,想到了自定义去实现但是思路不是很明确,跟老大请教了下,给了我思路就开始上手,但是还是出不来想要的效果,最后功夫不负有心人啊,上效果图吧,Android 仿微信聊天气泡_第1张图片

参考文档:https://segmentfault.com/a/1190000006753544,

这是一个自定义组合空间,可以往里面放任何控件,自定义9patch效果.

public class ChatItemLayout extends FrameLayout {
    private int resourceId;
    private Context mContext;
    private Bitmap mMaskBitmap;
    private Paint mPaint;

    public ChatItemLayout(@NonNull Context context) {
        this(context,null);
    }

    public ChatItemLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);

    }

    public ChatItemLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChatItemLayout);
        resourceId = typedArray.getResourceId(R.styleable.ChatItemLayout_background_src, R.drawable.talk_blue_bg);
        typedArray.recycle();
        mContext = context;
        mPaint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() <= 0) {
            return;
        }
        int child_height = getChildAt(0).getMeasuredHeight();
        int measuredWidth = getChildAt(0).getMeasuredWidth();
        if (mMaskBitmap != null && !mMaskBitmap.isRecycled()) {
            mMaskBitmap.recycle();
            mMaskBitmap = null;
        }
        if (mMaskBitmap == null) {
            mMaskBitmap = getMask(measuredWidth, child_height);
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        try {

            drawMirrorBitmap(canvas);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void drawMirrorBitmap(Canvas canvas) {
        canvas.saveLayerAlpha(0.0F, 0.0F, getMeasuredWidth(), getMeasuredHeight(), 250, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(mMaskBitmap, 0.0f, 0.0f, mPaint);
//        canvas.restoreToCount(i);

    }



    private Bitmap getMask(int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);
        Drawable mask = mContext.getResources().getDrawable(resourceId);
        mask.setBounds(0, 0, width, height);
        mask.draw(canvas);
        return bitmap;
    }

这是刚出来效果,还没有进一步的优化,等后面再优化吧

你可能感兴趣的:(Android 仿微信聊天气泡)