Android程序设计-圆形图片的实现
在android中,google只提供了对图形的圆形操作,而没有实现对图片的圆形操作,所以我们无法实现上述操作,在此我们将使用框架进行设计(下述框架为as编写):
https://github.com/monsterLin/RoundedImageView
https://github.com/pungrue26/SelectableRoundedImageView
https://github.com/hdodenhof/CircleImageView
https://github.com/MostafaGazar/CustomShapeImageView
https://github.com/siyamed/android-shape-imageview
下面我们通过使用RoundedImageView来是实现这种效果:
首先我们在项目中导入开源框架:
导入成功后-
第一种方式:直接书写xml文件:
<com.makeramen.roundedimageview.RoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/imageView1" android:layout_width="40dp" android:layout_height="40dp" android:src="@drawable/photo" app:riv_corner_radius="30dip" app:riv_border_width="2dip" app:riv_border_color="#333333" app:riv_mutate_background="true" app:riv_oval="true" />
第二种方式:通过代码实现:
public static class RoundedDrawable extends Drawable { protected final float cornerRadius; protected final int margin; protected final RectF mRect = new RectF(), mBitmapRect; protected final BitmapShader bitmapShader; protected final Paint paint; public RoundedDrawable(Bitmap bitmap, int cornerRadius, int margin) { this.cornerRadius = cornerRadius; this.margin = margin; bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapRect = new RectF (margin, margin, bitmap.getWidth() - margin, bitmap.getHeight() - margin); paint = new Paint(); paint.setAntiAlias(true); paint.setShader(bitmapShader); } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); mRect.set(margin, margin, bounds.width() - margin, bounds.height() - margin); // Resize the original bitmap to fit the new bound Matrix shaderMatrix = new Matrix(); shaderMatrix.setRectToRect(mBitmapRect, mRect, Matrix.ScaleToFit.FILL); bitmapShader.setLocalMatrix(shaderMatrix); } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mRect, cornerRadius, cornerRadius, paint); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { paint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { paint.setColorFilter(cf); } } imageAware.setImageDrawable(new RoundedDrawable(bitmap, cornerRadius, margin));
附录:
eclipse的开源框架:https://files.cnblogs.com/files/boy1025/roundedimageview.zip