本文實(shí)例講述了Android編程實(shí)現(xiàn)自定義ImageView圓圖功能的方法。分享給大家供大家參考,具體如下:
首先很感謝開源項(xiàng)目Universal Image Loader圖片加載框架。之前也看過一段時(shí)間框架源碼,但是卻沒有時(shí)間進(jìn)行知識(shí)點(diǎn)的總結(jié)。
今天項(xiàng)目遇到了需要實(shí)現(xiàn)圓頭像的編輯顯示,Universal就已經(jīng)提供了這個(gè)顯示RoundedBitmapDisplayer這個(gè)類實(shí)現(xiàn)了圓圖功能??此拇a可以發(fā)現(xiàn)是實(shí)現(xiàn)的Drawable
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); } }