如何使用Glide库将图像裁剪成圆形?

238

有人知道如何使用Glide显示圆角图片吗?

我正在使用Glide加载一张图片,但是不知道如何将圆角参数传递给这个库。

我需要像以下示例一样显示图片:

图片描述


2
我使用了 https://github.com/hdodenhof/CircleImageView 来实现圆形图片视图。 - MilapTank
2
我知道如何使用Glide库与CircleImageView,但我正在寻找只使用Glide库的可能方法。Glide库中是否有任何方法可以实现这一点,或者它不支持此功能? - SBotirov
28个回答

1
在这种情况下,我需要添加阴影,但是imageView的高度无法工作。
实现"com.github.bumptech.glide:glide:4.10.0"
XML
<FrameLayout
    android:id="@+id/fl_image"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_margin="10dp"
    android:background="@drawable/card_circle_background"
    android:elevation="8dp">

    <ImageView
        android:id="@+id/iv_item_employee"
        android:layout_width="60dp"
        android:layout_height="60dp"
        tools:background="@color/colorPrimary" />
</FrameLayout>

形状可绘制。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
     <solid android:color="@color/white"/>
</shape>

Glide配置
Glide.with(this)
    .asBitmap()
    .load(item.image)
    .apply(RequestOptions.circleCropTransform())
    .into(iv_item_employee)

1
在我的情况下,.apply(RequestOptions.circleCropTransform())(4.11)没有起作用。因为我试图将其与ImageButton一起使用。当我改用(可点击的)ImageView时,它起作用并且看起来我想要的样子。

1

Glide版本4.6.1

Glide.with(context)
.load(url)
.apply(RequestOptions.bitmapTransform(new CircleCrop()))
.into(imageView);

1
Jetpack Compose 中,你可以使用 Modifier.clip(CircleShape)。
以下是一个示例:
GlideImage(
     model = imageUrl,
     contentDescription = "",
     contentScale = ContentScale.Crop,
     modifier = Modifier
     .size(20.dp)
     .clip(CircleShape)
)

0

简单解决方案 使用这个库 implementation 'de.hdodenhof:circleimageview:3.1.0'

<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profile_image"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="@drawable/profile"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"/>

Glide.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.animate(R.anim.fade_in)
.into(YourImageView);

0
                Glide.with(MainActivity.this)
                        .load(personPhoto)
                        .transition(withCrossFade(500))
                        .apply(RequestOptions.circleCropTransform())
                        .thumbnail(0.5f)
                        .into(imageView);

            

0
不要附加太多的功能,比如placeholder(),transition()等,只需像这段代码一样简单,它就能正常工作。
                        Glide.with(mContext)
                            .load(datas.getUser_img())
                            .centerCrop()
                            .into(ivAvator);

0

你需要使用CircularImageView来显示这种类型的图片...

你正在使用Glide库来加载图片...

在你的项目中创建一个ClassFile并将其加载到ImageView中...你将获得所需的结果...

尝试以下代码...

XML

 <com.yourpackage.CircularImageView
    android:id="@+id/imageview"
    android:layout_width="96dp"
    android:layout_height="96dp"
    app:border="true"
    app:border_width="3dp"
    app:border_color="@color/white"
    android:src="@drawable/image" />

CircularImageView.java

public class CircularImageView extends ImageView {
    private int borderWidth;
    private int canvasSize;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;

    public CircularImageView(final Context context) {
        this(context, null);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.circularImageViewStyle);
    }

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

        // init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        paintBorder.setAntiAlias(true);

        // load the styled attributes and set their properties
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);

        if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
            int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
            setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
            setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
        }

        if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
            addShadow();
    }

    public void setBorderWidth(int borderWidth) {
        this.borderWidth = borderWidth;
        this.requestLayout();
        this.invalidate();
    }

    public void setBorderColor(int borderColor) {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);
        this.invalidate();
    }

    public void addShadow() {
        setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
        // load the bitmap
        image = drawableToBitmap(getDrawable());

        // init shader
        if (image != null) {

            canvasSize = canvas.getWidth();
            if(canvas.getHeight()<canvasSize)
                canvasSize = canvas.getHeight();

            BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);

            // circleCenter is the x or y of the view's center
            // radius is the radius in pixels of the cirle to be drawn
            // paint contains the shader that will texture the shape
            int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // The parent has determined an exact size for the child.
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // The parent has not imposed any constraint on the child.
            result = canvasSize;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // Measure the text (beware: ascent is a negative number)
            result = canvasSize;
        }

        return (result + 2);
    }

    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

注意:

你可以使用

CircularImageView imgIcon = (CircularImageView)findViewById(R.id.imageview);

或者

ImageView imgIcon = (ImageView)findViewById(R.id.imageview);

它不会影响您的其他库……不必更改下载图像或其他任何内容的代码…… 它可以简单地使用XML定义……


3
我尝试过使用Glide + CircularImageView(以及RoundedImageView),但如果您开始使用占位符(当您正在下载图像时)和外观动画,它不起作用。 Picasso没有这个问题。 您可以在此处阅读更多信息:https://github.com/vinc3m1/RoundedImageView/issues/76 - zmicer
只需在Glide调用中使用.asBitmap,它就可以正常工作。 - granko87
需要在Glide上调用.dontAnimate(),这是不可接受的。 - Greg Ennis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接