// Resize the original bitmap to fit the new bound
Matrix shaderMatrix = new Matrix();
shaderMatrix.setRectToRect(mBitmapRect, mRect, Matrix.ScaleToFit.FILL);
bitmapShader.setLocalMatrix(shaderMatrix);
最后我要实现的是继承ImageView实现圆图
[java] view plain copy
public class URoundedImageView extends ImageView {
private Paint mBitmapPaint,mBackgroundPaint;
private BitmapShader mBitmapShader;
private RectF mBitmapRect , mRect;
private int borderWidth;
private Bitmap mBitmap;
private Matrix shaderMatrix;
public URoundedImageView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public URoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public URoundedImageView(Context context) {
super(context);
init();
}
private void init(){
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setColor(Color.WHITE);
borderWidth = 5;
mRect = new RectF();
shaderMatrix = new Matrix();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
// TODO Auto-generated method stub
super.onLayout(changed, left, top, right, bottom);
}
刚开始写的不够规范,直接在ondraw方法里面new一些需要的对象,lint提醒我们Avoid object allocations during draw/layout operations (preallocate and reuse instead)这个warning。因为ondraw会不断调用,如果一直new对象的话会吃内存。所以为了避免重复new对象,根据自己的需求进行判空操作。具体根据自己需求来优化代码,有时候为了达到需求也没办法做到在ondraw方法里不出现重复new对象的现象。