0
回答
为ImageView添加多彩的阴影
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

有一天想为ImageView添加阴影效果,但是单单的灰色阴影,不好看,试着实现根据图片颜色添加对应阴影颜色的ImageView,先看下效果

核心代码:

 @Override
    protected void dispatchDraw(Canvas canvas) {
        View view = getChildAt(0);
        if (null == view) {
            return;
        }
        canvas.save();

        mShadowRadiusSize = view.getHeight() / 12 > MAX_SHADOW_RADIUS_SIZE ? MAX_SHADOW_RADIUS_SIZE : view.getHeight() / 12;
        mShadowDepth = view.getHeight() / 16 > MAX_SHADOW_DEPTH ? MAX_SHADOW_DEPTH : view.getHeight() / 16;


        if (((ImageView) view).getDrawable() instanceof ClipDrawable) {
            mShadowRGB = Color.parseColor(DEFAULT_SHADOW_COLOR);
            mPaintShadow.setShadowLayer(mShadowRadiusSize, 0, mShadowDepth, getDarkerColor(mShadowRGB));
        } else if (((ImageView) view).getDrawable() instanceof ColorDrawable) {
            mShadowRGB = ((ColorDrawable) ((ImageView) view).getDrawable()).getColor();
            mPaintShadow.setShadowLayer(MAX_SHADOW_RADIUS_SIZE, 0, MAX_SHADOW_DEPTH, getDarkerColor(mShadowRGB));
        } else {
            mBitmap = ((BitmapDrawable) ((ImageView) view).getDrawable()).getBitmap();
            mSwatch = Palette.from(mBitmap).generate().getDominantSwatch();

            if (null != mSwatch) {
                mShadowRGB = mSwatch.getRgb();
            } else {
                mShadowRGB = Color.parseColor(DEFAULT_SHADOW_COLOR);
            }

            mPaintShadow.setShadowLayer(mShadowRadiusSize, 0, mShadowDepth, getDarkerColor(mShadowRGB));
            mBitmapTemp = Bitmap.createBitmap(mBitmap, 0, mBitmap.getHeight() / 4 * 3,mBitmap.getWidth(), mBitmap.getHeight() / 4);

            if (null != Palette.from(mBitmapTemp).generate().getDominantSwatch()) {
                mShadowRGB = Palette.from(mBitmapTemp).generate().getDominantSwatch().getRgb();
                mPaintShadow.setShadowLayer(mShadowRadiusSize, 0, mShadowDepth, mShadowRGB);
            }
        }
        mRectF = new RectF(view.getX() + (view.getWidth() / 20), view.getY(), view.getX() + view.getWidth() - (view.getWidth() / 20), view.getY() + view.getHeight());
        canvas.drawRoundRect(mRectF, mCornerRadius, mCornerRadius, mPaintShadow);
        canvas.restore();
        ((CustomImageView) view).setCornerRadius(mCornerRadius);
        super.dispatchDraw(canvas);
    }

源码地址:https://github.com/DingMouRen/PaletteImageView

举报
钉某人
发帖于8个月前 0回/425阅
顶部