技术干货自定义控件

圆形 ImageView 的实现方法

2015-03-19  本文已影响678人  lguipeng

废话不多说,直接上代码

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));

实现效果图如下


上一篇 下一篇

猜你喜欢

热点阅读