3

我看过 Udacity 关于 Material Design 的讲座,并提到了使用RoundedBitmapDrawable来实现圆形视图。但是我有一些麻烦使它与Picasso.

我不确定究竟是如何Picasso工作的,但我在文件存储中有很大的非方形图像。因此我使用Picasso如下:

Picasso.with(context).load(f).resize(densityDpi, densityDpi).centerInside().transform(new Transformation() {
    @Override
    public Bitmap transform(Bitmap source) {
        Log.d("jano", "transformation running");
        RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), source);
        drawable.setCircular(true);
        drawable.setCornerRadius(source.getWidth() / 2.0f);
        return drawable.getBitmap();
    }

    @Override
    public String key() {
        return "circle";
    }
}).into(imageView);

然而,图像是正方形的,没有圆角(应该是圆形的)。这就是我想要实现的目标。

是否有任何简单的方法可以实现这一目标,RoundedBitmapDrawable或者我必须完全实现转换?(我在 StackOverflow 上看到过)

请不要在没有说明为什么不能使用的情况下提交答案。我只想知道这 2 项的组合 ( Picasso, RoundedBitmapDrawable)

4

4 回答 4

3

我尝试了很多做同样的事情但也没有工作......我猜是getBitmap期间的一个问题,无论如何,我解决了这个问题:(注意主要区别是我使用setImage作为drawable而不是转换正如我所说的到位图)

    Picasso.with(getContext())
    .load(mUser.user.profileImageUrl)
    .into(mProfileImage, new Callback() {
        @Override
        public void onSuccess() {
            Bitmap source = ((BitmapDrawable) mProfileImage.getDrawable()).getBitmap();
            RoundedBitmapDrawable drawable =
                    RoundedBitmapDrawableFactory.create(getContext().getResources(), source);
            drawable.setCircular(true);
            drawable.setCornerRadius(Math.max(source.getWidth() / 2.0f, source.getHeight() / 2.0f));
            mProfileImage.setImageDrawable(drawable);
        }

        @Override
        public void onError() {

        }
    });
于 2016-01-28T12:02:11.427 回答
0

我通过实现这样的目标(而不是直接使用 .into(ImageView))为使用 RoundedBitmapDrawable 制定了解决方案

    Picasso.with(context)
                    .load("https://something.png")
                    .into( RoundCornersTargetProxy(my_avatar_imageview, 8f) )

目标实现如下

    class RoundCornersTargetProxy(val view: ImageView, val radius: Float): Target {
        override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
            view.setImageDrawable(placeHolderDrawable)
        }

        override fun onBitmapFailed(errorDrawable: Drawable?) {
            view.setImageDrawable(errorDrawable)
        }

        override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom?) {
            RoundedBitmapDrawableFactory.create(Resources.getSystem(), bitmap).let {
                it.cornerRadius = radius
                view.setImageDrawable(it)
            }
        }

    }

这样您就不必在 imageview 中设置它只是为了再次将其取出。

于 2019-11-14T11:38:25.500 回答
0

我花了几个小时处理完全相同的问题。它返回相同的非圆形图像的原因是因为它首先传递了一个非圆形的位图。

RoundedBitmapDrawable的文档中:

获取位图()

返回此可绘制对象用于渲染的位图。

所以意思是返回原始的未转换的位图。

解决方案:什么都没有!我最终使用了一个很棒的库picasso -transformationsCropCircleTransformation()

例子:

 Picasso.with(mContext).load(url)
            .transform(new CropCircleTransformation())
            .into(holder_image);
于 2016-07-15T19:48:29.597 回答
0

您可以使用与 Picasso 库配合良好的 google IO 应用程序 BezelImageView,只需将此类添加到您的项目中,您就可以像任何其他图像视图一样直接开始使用它,但是 bezelImageView 有 2 个额外的选项来指定圆形边框颜色和蒙版可绘制的。链接到这里的源代码。

BezelImageView.java

/*
 * Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.apps.iosched.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.google.samples.apps.iosched.R;

/**
 * An {@link android.widget.ImageView} that draws its contents inside a mask and draws a border
 * drawable on top. This is useful for applying a beveled look to image contents, but is also
 * flexible enough for use with other desired aesthetics.
 */
public class BezelImageView extends ImageView {
    private Paint mBlackPaint;
    private Paint mMaskedPaint;

    private Rect mBounds;
    private RectF mBoundsF;

    private Drawable mBorderDrawable;
    private Drawable mMaskDrawable;

    private ColorMatrixColorFilter mDesaturateColorFilter;
    private boolean mDesaturateOnPress = false;

    private boolean mCacheValid = false;
    private Bitmap mCacheBitmap;
    private int mCachedWidth;
    private int mCachedHeight;

    public BezelImageView(Context context) {
        this(context, null);
    }

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

    public BezelImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Attribute initialization.
        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView,
                defStyle, 0);

        mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable);
        if (mMaskDrawable != null) {
            mMaskDrawable.setCallback(this);
        }

        mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable);
        if (mBorderDrawable != null) {
            mBorderDrawable.setCallback(this);
        }

        mDesaturateOnPress = a.getBoolean(R.styleable.BezelImageView_desaturateOnPress,
                mDesaturateOnPress);

        a.recycle();

        // Other initialization.
        mBlackPaint = new Paint();
        mBlackPaint.setColor(0xff000000);

        mMaskedPaint = new Paint();
        mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // Always want a cache allocated.
        mCacheBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);

        if (mDesaturateOnPress) {
            // Create a desaturate color filter for pressed state.
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);
            mDesaturateColorFilter = new ColorMatrixColorFilter(cm);
        }
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        final boolean changed = super.setFrame(l, t, r, b);
        mBounds = new Rect(0, 0, r - l, b - t);
        mBoundsF = new RectF(mBounds);

        if (mBorderDrawable != null) {
            mBorderDrawable.setBounds(mBounds);
        }
        if (mMaskDrawable != null) {
            mMaskDrawable.setBounds(mBounds);
        }

        if (changed) {
            mCacheValid = false;
        }

        return changed;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mBounds == null) {
            return;
        }

        int width = mBounds.width();
        int height = mBounds.height();

        if (width == 0 || height == 0) {
            return;
        }

        if (!mCacheValid || width != mCachedWidth || height != mCachedHeight) {
            // Need to redraw the cache.
            if (width == mCachedWidth && height == mCachedHeight) {
                // Have a correct-sized bitmap cache already allocated. Just erase it.
                mCacheBitmap.eraseColor(0);
            } else {
                // Allocate a new bitmap with the correct dimensions.
                mCacheBitmap.recycle();
                //noinspection AndroidLintDrawAllocation
                mCacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                mCachedWidth = width;
                mCachedHeight = height;
            }

            Canvas cacheCanvas = new Canvas(mCacheBitmap);
            if (mMaskDrawable != null) {
                int sc = cacheCanvas.save();
                mMaskDrawable.draw(cacheCanvas);
                mMaskedPaint.setColorFilter((mDesaturateOnPress && isPressed())
                        ? mDesaturateColorFilter : null);
                cacheCanvas.saveLayer(mBoundsF, mMaskedPaint,
                        Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
                super.onDraw(cacheCanvas);
                cacheCanvas.restoreToCount(sc);
            } else if (mDesaturateOnPress && isPressed()) {
                int sc = cacheCanvas.save();
                cacheCanvas.drawRect(0, 0, mCachedWidth, mCachedHeight, mBlackPaint);
                mMaskedPaint.setColorFilter(mDesaturateColorFilter);
                cacheCanvas.saveLayer(mBoundsF, mMaskedPaint,
                        Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
                super.onDraw(cacheCanvas);
                cacheCanvas.restoreToCount(sc);
            } else {
                super.onDraw(cacheCanvas);
            }

            if (mBorderDrawable != null) {
                mBorderDrawable.draw(cacheCanvas);
            }
        }

        // Draw from cache.
        canvas.drawBitmap(mCacheBitmap, mBounds.left, mBounds.top, null);
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (mBorderDrawable != null && mBorderDrawable.isStateful()) {
            mBorderDrawable.setState(getDrawableState());
        }
        if (mMaskDrawable != null && mMaskDrawable.isStateful()) {
            mMaskDrawable.setState(getDrawableState());
        }
        if (isDuplicateParentStateEnabled()) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    @Override
    public void invalidateDrawable(Drawable who) {
        if (who == mBorderDrawable || who == mMaskDrawable) {
            invalidate();
        } else {
            super.invalidateDrawable(who);
        }
    }

    @Override
    protected boolean verifyDrawable(Drawable who) {
        return who == mBorderDrawable || who == mMaskDrawable || super.verifyDrawable(who);
    }
}

布局中的使用。

<com.google.samples.apps.iosched.ui.widget.BezelImageView
                android:id="@+id/session_photo"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:layout_gravity="center"
                android:scaleType="centerCrop"
                android:src="@drawable/dp"
                app:borderDrawable="@drawable/circle_stroke_only"
                app:maskDrawable="@drawable/circle_blue" />

circle_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <solid android:color="#00bcd4" />
</shape>

circle_stroke_only.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <stroke android:color="@color/theme_green" android:width="1dp"/>

</shape>
于 2015-10-27T09:56:33.860 回答