标签:
在很多应用中,我们看到,个人主页里面的头像一般都是圆的,设计成圆的会使整个界 面布 局变的优雅漂亮。那么,怎么使头像变圆呢?有的人说可以在上面加一个中间为透明圆形的png图,用它来遮盖住头像不就行了嘛,但是png四周始终始终是不 透明的,怎么做也达不到如下的效果图的。
下面我们讲讲怎么做成的吧。
首先创建一个继承ImageView的抽象类MaskedImage。让他重写onDraw方法。代码如下
然后新建一个类CircularImage继承MaskedImage。代码如下:
public class CircularImage extends MaskedImage { public CircularImage(Context paramContext) { super(paramContext); } public CircularImage(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public CircularImage(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); } public Bitmap createMask() { int i = getWidth(); int j = getHeight(); Bitmap.Config localConfig = Bitmap.Config.ARGB_8888; Bitmap localBitmap = Bitmap.createBitmap(i, j, localConfig); Canvas localCanvas = new Canvas(localBitmap); Paint localPaint = new Paint(1); localPaint.setColor(-16777216); float f1 = getWidth(); float f2 = getHeight(); RectF localRectF = new RectF(0.0F, 0.0F, f1, f2); localCanvas.drawOval(localRectF, localPaint); return localBitmap; } }
public class CircularImage extends MaskedImage { public CircularImage(Context paramContext) { super(paramContext); } public CircularImage(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public CircularImage(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); } public Bitmap createMask() { int i = getWidth(); int j = getHeight(); Bitmap.Config localConfig = Bitmap.Config.ARGB_8888; Bitmap localBitmap = Bitmap.createBitmap(i, j, localConfig); Canvas localCanvas = new Canvas(localBitmap); Paint localPaint = new Paint(1); localPaint.setColor(-16777216); float f1 = getWidth(); float f2 = getHeight(); RectF localRectF = new RectF(0.0F, 0.0F, f1, f2); localCanvas.drawOval(localRectF, localPaint); return localBitmap; } }
新建一个MainActivity,代码如下:
其XML布局文件为:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" > <ImageView android:layout_width="82.0dip" android:layout_height="82.0dip" android:layout_centerInParent="true" android:contentDescription="@null" android:src="@drawable/me_head_bg" /> <com.doublefi123.diary.widget.CircularImage android:id="@+id/cover_user_photo" android:layout_width="74.0dip" android:layout_height="74.0dip" android:layout_centerInParent="true" /> </RelativeLayout>
这样就OK啦。哈哈
源码在此:http://download.csdn.net/detail/doublefi123/5252186
标签:
原文地址:http://www.cnblogs.com/dongdong230/p/4275275.html