我已经成功使用Glide将图像加载到ImageView中,并使用.circularCrop()
方法进行裁剪。
Glide.with(this)
.load("https://i.imgur.com/QjQGiPj.jpeg")
.circleCrop()
.into(imageView);
我试图在加载的url失败时,使用.error(R.drawable.placeholder)
添加一个错误占位符Drawable
。
这样做的问题是错误占位符不会将错误图像裁剪成圆形。
成功加载:
未成功加载:
如何将.circleCrop()
应用于错误占位符图像?
我尝试为ImageView
添加一个圆形drawable背景,但这并不起作用。
bgr_circular
<?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"/>
<stroke android:width="1dp" android:color="@color/defaultHintColor"/>
</shape>
<ImageView
android:id="@+id/image_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/bgr_circular"/>
用于测试的代码:
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = findViewById(R.id.image_view);
Button button = findViewById(R.id.btn_test);
button.setOnClickListener(v -> {
Glide.with(this)
.load("https://i.imgur.com/QjQGiPj.jpe") //Test with incorrect url
.circleCrop()
.error(R.drawable.placeholder)
.into(imageView);
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Image"/>
<ImageView
android:id="@+id/image_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/bgr_circular"/>
</LinearLayout>
<?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"/>
<stroke android:width="1dp" android:color="@color/defaultHintColor"/>
</shape>
编辑1:__________________________________________________________
我尝试使用Glide在github中较旧的解决方案之一。
https://github.com/bumptech/glide/issues/1212#issuecomment-221751860
但这并不能完全解决问题。
Bitmap placeholder = BitmapFactory.decodeResource(this.getResources(), R.drawable.placeholder);
RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(this.getResources(), placeholder);
circularBitmapDrawable.setCircular(true);
Glide.with(this)
.load("https://i.imgur.com/QjQGiPj.jpe")
.circleCrop()
.error(circularBitmapDrawable)
.into(imageView);
CircularImageView
是材料库的一部分吗?我目前正在使用com.google.android.material:material:1.4.0
,但在 XML 中找不到它。还是它是第三方库? - DIRTY DAVEImageView
,因此是第三方库。如果您正在将错误可绘制对象显示在圆形形状上,请至少使用正方形图像以获得更好的比例。 - ADMCircleImageView
库在使用 Glide 加载错误占位符时表现得非常完美。它甚至可以完美地添加边框,所以我不再需要自定义 Drawable 类了。感谢您的推荐。 - DIRTY DAVE