具有实心颜色的圆形ImageView

4
CircularImageView(https://github.com/Pkmmte/CircularImageView)在设置位图时效果很好,像这样:circularImageView.setImageBitmap(bitmap);。然而,有时我只想设置一个纯色而不是位图。如果我这样做:circularImageView.setBackgroundResource(R.color.blue);,视图的颜色被设置了,但图像从未变成圆形,仍然填充整个矩形视图。 我认为getDrawable()返回null,因此无法实际操作视图。有人遇到过这个问题或者有任何建议吗?
编辑:
我可以这样做,但似乎有点脆弱:
Bitmap image = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
image.eraseColor(android.graphics.Color.GREEN);
circularImageView.setImageBitmap(image);
2个回答

2

你应该调用 circularImageView.setImageResource(R.color.blue)

你写的代码设置了视图的背景,而不是内容图片。从 github 上查看代码,这个视图只会将内容图片裁剪成圆形 - 它对背景没有任何影响。


CircularImageView类通过getDrawable()获取Drawable,但在Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);处崩溃,因为宽度和高度为0。看起来我必须指定一个宽度和高度,这就是我在上面的编辑中所做的。 - ono

1

尝试使用ColorDrawable

int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);

如果我使用 circularImageView.setBackground(new ColorDrawable(R.color.blue)),它不起作用。而且 setBackground(Drawable) 已被弃用。 - ono
是的,对于较新的API级别,setBackground已经被弃用,您应该使用setBackgroundDrawable(),这也应该适用于ColorDrawable是Drawable的子类。 - Onur A.

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