分享一个实现图片圆角,圆的自定义的ImageView,尽可能少的减少内存消耗。

本文介绍了如何在Android中实现自定义圆角、圆及上部分圆角的图片功能,包括不同类型的图片类型、圆角大小的设置以及绘制过程。
/**
 * 实现圆角、圆、上部分圆角的图片
 * 
 * @author
 *
 */
public class RoundRectImageView extends ImageView {
    // ======== 定义图片的类型 ===========//
    /**
     * 圆
     */
    public static final int TYPE_CIRCLE = 0;
    /**
     * 圆角方形
     */
    public static final int TYPE_ROUND = 1;
    /**
     * 上部分圆角方形
     */
    public static final int TYPE_ROUND_RECT = 2;
    // ======== 定义图片的类型 ===========//

    /**
     * 圆角大小的默认值
     */
    private static final int BODER_RADIUS_DEFAULT = 3;

    /**
     * 图片的类型:0 圆形;1 圆角;2 上部分圆角方形
     */
    private int mType;
    /**
     * 圆角的大小
     */
    private int mBorderRadius;

    /**
     * 绘图的Paint
     */
    private Paint mBitmapPaint;
    /**
     * 圆角的半径
     */
    private int mRadius;
    /**
     * 3x3 矩阵,主要用于缩小放大
     */
    private Matrix mMatrix;
    /**
     * 渲染图像,使用图像为绘制图形着色
     */
    private BitmapShader mBitmapShader;
    /**
     * view的宽度
     */
    private int mWidth;
    private RectF mRoundRect;

    public RoundRectImageView(Context context, AttributeSet attrs) {

	super(context, attrs);
	mMatrix = new Matrix();
	mBitmapPaint = new Paint();
	mBitmapPaint.setAntiAlias(true);

	// 默认圆角大小为BODER_RADIUS_DEFAULT
	mBorderRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT,
		getResources().getDisplayMetrics()); 
	// 默认为roundRect
	mType = TYPE_ROUND_RECT;
	// 默认取getMeasuredWidth()
	mWidth = getMeasuredWidth();

	if (attrs != null) {
	    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);

	    mBorderRadius = a.getDimensionPixelSize(R.styleable.RoundImageView_borderRadius, (int) TypedValue
		    .applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT, getResources()
			    .getDisplayMetrics())); // 默认为BODER_RADIUS_DEFAULT
	    mType = a.getInt(R.styleable.RoundImageView_type, TYPE_ROUND_RECT); // 默认为roundRect
	    
	    mWidth = a.getDimensionPixelSize(R.styleable.RoundImageView_circle_width, mWidth);

	    a.recycle();
	}

    }

    public RoundRectImageView(Context context) {
	this(context, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
	super.onMeasure(widthMeasureSpec, heightMeasureSpec);

	/**
	 * 如果类型是圆形,则强制改变view的宽高一致,以小值为准
	 */
	if (mType == TYPE_CIRCLE) {
	    if (mWidth == 0) {
		mWidth = getMeasuredWidth();
	    }
	    mRadius = mWidth / 2;
	    setMeasuredDimension(mWidth, mWidth);
	}

    }

    /**
     * 初始化BitmapShader
     */
    private void setUpShader() {
	Drawable drawable = getDrawable();
	if (drawable == null) {
	    return;
	}

	Bitmap bmp = drawableToBitamp(drawable);

	float scale = 1.0f;
	if (bmp != null) {
	    // 将bmp作为着色器,就是在指定区域内绘制bmp
	    mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP);
	    if (mType == TYPE_CIRCLE) {
		// 拿到bitmap宽或高的小值
		int bSize = Math.min(bmp.getWidth(), bmp.getHeight());
		scale = mWidth * 1.0f / bSize;

	    } else if (mType == TYPE_ROUND || mType == TYPE_ROUND_RECT) {
		if (!(bmp.getWidth() == getWidth() && bmp.getHeight() == getHeight())) {
		    // 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
		    scale = Math.max(getWidth() * 1.0f / bmp.getWidth(), getHeight() * 1.0f / bmp.getHeight());
		}
	    }
	}
	// shader的变换矩阵,我们这里主要用于放大或者缩小
	mMatrix.setScale(scale, scale);
	// 设置变换矩阵
	mBitmapShader.setLocalMatrix(mMatrix);
	// 设置shader
	mBitmapPaint.setShader(mBitmapShader);
    }

    @Override
    protected void onDraw(Canvas canvas) {
	// Log.e("TAG", "onDraw");
	if (getDrawable() == null) {
	    return;
	}
	setUpShader();

	if (mType == TYPE_ROUND || mType == TYPE_ROUND_RECT) {
	    canvas.drawRoundRect(mRoundRect, mBorderRadius, mBorderRadius, mBitmapPaint);
	    // 最下方覆盖一层长方形,使图片看起来像 只有上面圆角的 样式
	} else {
	    canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint);
	    // drawSomeThing(canvas);
	}
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
	super.onSizeChanged(w, h, oldw, oldh);

	// 圆角图片的范围
	if (mType == TYPE_ROUND) {
	    mRoundRect = new RectF(0, 0, w, h);
	} else if (mType == TYPE_ROUND_RECT) {
	    mRoundRect = new RectF(0, 0, w, h + mBorderRadius);
	}
    }

    /**
     * drawable转bitmap
     * 
     * @param drawable
     * @return
     */
    private Bitmap drawableToBitamp(Drawable drawable) {
	if (drawable instanceof BitmapDrawable) {
	    BitmapDrawable bd = (BitmapDrawable) drawable;
	    return bd.getBitmap();
	}
	int w = drawable.getIntrinsicWidth();
	int h = drawable.getIntrinsicHeight();
	Bitmap bitmap = null;
	try {
	    bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
	} catch (OutOfMemoryError e) {
	    e.printStackTrace();
	    recycle(bitmap);
	    try {
		bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
	    } catch (OutOfMemoryError e1) {
		e1.printStackTrace();
		recycle(bitmap);
	    }
	}
	if (bitmap != null) {
	    Canvas canvas = new Canvas(bitmap);
	    drawable.setBounds(0, 0, w, h);
	    drawable.draw(canvas);
	}
	return bitmap;
    }

    public static void recycle(Bitmap bitmap) {
	if (null != bitmap && !bitmap.isRecycled()) {
	    bitmap.recycle();
	    bitmap = null;
	}
    }

    private static final String STATE_INSTANCE = "state_instance";
    private static final String STATE_TYPE = "state_type";
    private static final String STATE_BORDER_RADIUS = "state_border_radius";

    @Override
    protected Parcelable onSaveInstanceState() {
	Bundle bundle = new Bundle();
	bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState());
	bundle.putInt(STATE_TYPE, mType);
	bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius);
	return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
	if (state instanceof Bundle) {
	    Bundle bundle = (Bundle) state;
	    super.onRestoreInstanceState(((Bundle) state).getParcelable(STATE_INSTANCE));
	    this.mType = bundle.getInt(STATE_TYPE);
	    this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS);
	} else {
	    super.onRestoreInstanceState(state);
	}

    }

    /**
     * 设置圆角、圆的半径
     * 
     * @param borderRadius
     */
    public void setBorderRadius(int borderRadius) {
	int pxVal = dp2px(borderRadius);
	if (this.mBorderRadius != pxVal) {
	    this.mBorderRadius = pxVal;
	    invalidate();
	}
    }

    /**
     * 设置图片的显示形状
     * 
     * @param type
     */
    public void setType(int type) {
	if (this.mType != type) {
	    this.mType = type;
	    if (this.mType != TYPE_ROUND && this.mType != TYPE_CIRCLE && this.mType != TYPE_ROUND_RECT) {
		this.mType = TYPE_CIRCLE;
	    }
	    requestLayout();
	}

    }

    public int dp2px(int dpVal) {
	return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值