我创建了一个CircularImageView这个问题:Create circular image view in android如何在圆形图像上添加阴影和边框androidView?
下载项目上GitHub
1)这是CircularImageView类:
public class CircularImageView extends ImageView {
public CircularImageView(Context context) {
super(context);
}
public CircularImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable)drawable).getBitmap() ;
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
Bitmap roundBitmap = getCroppedBitmap(bitmap, getWidth());
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if(bmp.getWidth() != radius || bmp.getHeight() != radius)
sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
else
sbmp = bmp;
Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(), Bitmap.Config.ARGB_8888);
final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(Color.parseColor("#BAB399"));
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
c.drawCircle(sbmp.getWidth()/2+0.7f, sbmp.getHeight()/2+0.7f, sbmp.getWidth()/2+0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
c.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
2)我在我的布局中使用这样的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccccc"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<com.mikhaellopez.circularimageview.CircularImageView
android:id="@+id/imageViewCircular"
android:layout_width="@dimen/image_view_size"
android:layout_height="@dimen/image_view_size"
android:layout_gravity="center"
android:background="@drawable/border"
android:src="@drawable/image" />
</LinearLayout>
3)当前结果图片:
如何改变这种代码有一个影子在我的ImageView圆形边界?
的Objectif结果:
编辑2015年10月15日:
您可以使用或下载我的GitHub库CircularImageView与所有修补程序通过使用gradle depend ency:
compile 'com.mikhaellopez:circularimageview:2.0.1'
我不知道你在做什么样的应用程序,但它看起来很棒 – Jameo
@ lopez.mikhael你的代码有效,它非常好!但是它有可能在宽度和高度上使用wrap_content?我尝试过时会崩溃。 –
@DanielNazareth你说得对,目前无法在宽度和高度上使用wrap_content。我没有时间去改变它。麻烦来自我使用图像的尺寸绘制圆圈。使用wrap_content我会丢失这些信息。问题会解决的,我会提醒你。 –