標籤:
在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的開源架構:http://files.cnblogs.com/files/boy1025/roundedimageview.zip
Android程式設計-圓形圖片的實現