Android 如何使用 Glide 库对图像进行四舍五入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25278821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round an image with Glide library?
提问by mr.boyfox
So, anybody know how to display an image with rounded corners with Glide? I am loading an image with Glide, but I don't know how to pass rounded params to this library.
那么,有人知道如何使用 Glide 显示带圆角的图像吗?我正在使用 Glide 加载图像,但我不知道如何将舍入参数传递给该库。
I need display image like following example:
我需要像以下示例一样显示图像:
回答by jimmy0251
Glide V4:
滑翔V4:
Glide.with(context)
.load(url)
.centerCrop()
.into(imageView);
Glide V3:
滑翔V3:
You can use RoundedBitmapDrawable
for circular images with Glide. No custom ImageView is required.
您可以将RoundedBitmapDrawable
Glide 用于圆形图像。不需要自定义 ImageView。
Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
imageView.setImageDrawable(circularBitmapDrawable);
}
});
回答by Harsha Vardhan
Check this post, glide vs picasso...
Edit: the linked post doesn't call out an important difference in the libraries. Glide does the recycling automatically. See TWiStErRob's commentfor more.
检查这篇文章,glide vs picasso...
编辑:链接的文章没有指出库中的重要区别。Glide 会自动进行回收。有关更多信息,请参阅TWiStErRob 的评论。
Glide.with(this).load(URL).transform(new CircleTransform(context)).into(imageView);
public static class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
}
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
回答by Roman Samoylenko
The easiest way (requires Glide 4.x.x)
最简单的方法(需要 Glide 4.xx)
Glide.with(context).load(uri).apply(RequestOptions().circleCrop()).into(imageView)
回答by PathoS
Try this way
试试这个方法
code
代码
Glide.with(this)
.load(R.drawable.thumbnail)
.bitmapTransform(new CropCircleTransformation(this))
.into(mProfile);
XML
XML
<ImageView
android:id="@+id/img_profile"
android:layout_width="76dp"
android:layout_height="76dp"
android:background="@drawable/all_circle_white_bg"
android:padding="1dp"/>
all_circle_white_bg.xml
all_circle_white_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@android:color/white"/>
</shape>
</item>
</selector>
- I use this transformation library. -> https://github.com/wasabeef/glide-transformations
- Circle stroke width is ImageView's padding
- 我使用这个转换库。-> https://github.com/wasabeef/glide-transformations
- 圆形笔画宽度是ImageView的padding
回答by Greg Ennis
The other solutions did not work for me. I found they all have significant drawbacks:
其他解决方案对我不起作用。我发现它们都有明显的缺点:
- Solutions using glide transformations do not work with placeholders
- Solutions using rounded image views do not work with animations (i.e. crossfade)
- Solutions using a generic method of a parent that clips its children (i.e. the accepted answer here) do not work well with glide
- 使用滑动变换的解决方案不适用于占位符
- 使用圆形图像视图的解决方案不适用于动画(即淡入淡出)
- 使用剪辑其子项的父项的通用方法(即此处接受的答案)的解决方案不适用于 glide
It is really interesting that after fumbling around with this I found the Fresco library page about rounded corners and circlesin which they list basically the same limitations and conclude with the statement:
非常有趣的是,在摸索之后,我找到了关于圆角和圆的Fresco 库页面,其中列出了基本相同的限制并以声明结束:
there is no really good solution for rounding corners on Android and one has to choose between the aforementioned trade-offs
在 Android 上没有真正好的圆角解决方案,必须在上述权衡之间进行选择
Unbelievable that at this time we still dont have a real solution. I have an alternate solution based on the link I put above. The drawback with this approach is that it assumes your background is a solid color (the corners aren't really transparent). You would use it like this:
令人难以置信的是,此时我们仍然没有真正的解决方案。我有一个基于我上面提供的链接的替代解决方案。这种方法的缺点是它假设您的背景是纯色(角落不是真正透明)。你会像这样使用它:
<RoundedCornerLayout ...>
<ImageView ...>
</RoundedCornerLayout>
The gist is hereand full code here:
要点在这里,完整代码在这里:
public class RoundedCornerLayout extends RelativeLayout {
private Bitmap maskBitmap;
private Paint paint;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
setWillNotDraw(false);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (maskBitmap == null) {
// This corner radius assumes the image width == height and you want it to be circular
// Otherwise, customize the radius as needed
cornerRadius = canvas.getWidth() / 2;
maskBitmap = createMask(canvas.getWidth(), canvas.getHeight());
}
canvas.drawBitmap(maskBitmap, 0f, 0f, paint);
}
private Bitmap createMask(int width, int height) {
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mask);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE); // TODO set your background color as needed
canvas.drawRect(0, 0, width, height, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint);
return mask;
}
}
回答by MilapTank
its very simple i have seen Glide library its very good library and essay base on volley Google's library
它非常简单,我已经看到 Glide 图书馆它非常好的图书馆和基于 volley Google 图书馆的论文
usethis library for rounded image view
使用此库进行圆形图像视图
https://github.com/hdodenhof/CircleImageView
https://github.com/hdodenhof/CircleImageView
now
现在
//For a simple view:
//对于一个简单的视图:
@Override
public void onCreate(Bundle savedInstanceState) {
...
CircleImageView civProfilePic = (CircleImageView)findViewById(R.id.ivProfile);
Glide.load("http://goo.gl/h8qOq7").into(civProfilePic);
}
//For a list:
//对于一个列表:
@Override
public View getView(int position, View recycled, ViewGroup container) {
final ImageView myImageView;
if (recycled == null) {
myImageView = (CircleImageView) inflater.inflate(R.layout.my_image_view,
container, false);
} else {
myImageView = (CircleImageView) recycled;
}
String url = myUrls.get(position);
Glide.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.animate(R.anim.fade_in)
.into(myImageView);
return myImageView;
}
and in XML
并在 XML 中
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/ivProfile
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_centerInParent="true"
android:src="@drawable/hugh"
app:border_width="2dp"
app:border_color="@color/dark" />
回答by Prashant Gosai
Now in Glide V4 you can directly use CircleCrop()
现在在 Glide V4 中你可以直接使用 CircleCrop()
Glide.with(fragment)
.load(url)
.circleCrop()
.into(imageView);
Built in types
内置类型
- CenterCrop
- FitCenter
- CircleCrop
- 中心裁剪
- 健身中心
- 圆形裁剪
回答by Basi
For Glide 4.x.x
对于Glide 4.xx
use
用
Glide
.with(context)
.load(uri)
.apply(
RequestOptions()
.circleCrop())
.into(imageView)
from docit stated that
从doc它说
Round Pictures: CircleImageView/CircularImageView/RoundedImageView are known to have issueswith TransitionDrawable (.crossFade() with .thumbnail() or .placeholder()) and animated GIFs, use a BitmapTransformation(.circleCrop() will be available in v4) or .dontAnimate() to fix the issue
圆形图片:CircleImageView / CircularImageView / RoundedImageView已知有问题与TransitionDrawable(.crossFade()与.thumbnail()或.placeholder())和GIF动画,使用 BitmapTransformation(.circleCrop()将在V4使用)或.dontAnimate() 来解决这个问题
回答by ROHIT PARMAR
Use this transformation, it will work fine.
使用此转换,它将正常工作。
public class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int borderColor = ColorUtils.setAlphaComponent(Color.WHITE, 0xFF);
int borderRadius = 3;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
if (squared != source) {
source.recycle();
}
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
// Prepare the background
Paint paintBg = new Paint();
paintBg.setColor(borderColor);
paintBg.setAntiAlias(true);
// Draw the background circle
canvas.drawCircle(r, r, r, paintBg);
// Draw the image smaller than the background so a little border will be seen
canvas.drawCircle(r, r, r - borderRadius, paint);
squared.recycle();
return result;
}
@Override
public String getId() {
return getClass().getName();
}}
回答by Anand Savjani
I found one easy and simple solution for add border over imageview in which color want to set or add gradient over image.
我找到了一种简单的解决方案,可以在 imageview 上添加边框,其中颜色要设置或在图像上添加渐变。
STEPS:
脚步:
- Take one frame layout and add two images.You can set size as per your requirement. For
imgPlaceHolder
, you need one white image or color which you want to set.
- 采取一帧布局并添加两个图像。您可以根据需要设置大小。对于
imgPlaceHolder
,您需要一张想要设置的白色图像或颜色。
<ImageView
android:id="@+id/imgPlaceHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:src="@drawable/white_bg"/>
<ImageView
android:id="@+id/imgPic"
android:layout_width="190dp"
android:layout_height="190dp"
android:layout_gravity="center"
android:src="@drawable/image01"/>
</FrameLayout>
After placing this code on xml file , put below line in java file.
Glide.with(this).load(R.drawable.image01).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPic) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); imageView.setImageDrawable(circularBitmapDrawable); } }); Glide.with(this).load(R.drawable.white_bg).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPlaceHolder) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); imgTemp2.setImageDrawable(circularBitmapDrawable); } });
将此代码放在 xml 文件上后,将下面的行放在 java 文件中。
Glide.with(this).load(R.drawable.image01).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPic) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); imageView.setImageDrawable(circularBitmapDrawable); } }); Glide.with(this).load(R.drawable.white_bg).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPlaceHolder) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource); circularBitmapDrawable.setCircular(true); imgTemp2.setImageDrawable(circularBitmapDrawable); } });
This will make border of imageview simply with out any extra padding and margin.
这将使图像视图的边框简单而没有任何额外的填充和边距。
NOTE: White image is compulsory for border otherwise it will not work.
注意:边框必须使用白色图像,否则将无法使用。
Happy codding :)
快乐编码:)