圓形 ImageView 的實現方法

weixin_34337265發表於2015-03-19

廢話不多說,直接上程式碼

public class CircleDrawable 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;
            protected float center;

            public CircleDrawable(Bitmap bitmap, float center, int cornerRadius, int margin) {
                this.cornerRadius = cornerRadius;
                this.margin = margin;
                this.center = center;
                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.drawCircle(center, center, 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);
            }
        }
imageView.setImageDrawable(new CircleDrawable(bitmap, center, cornerRadius, margin));

實現效果圖如下


291805-dbff65ac04510eb1.PNG

相關文章