有時顯示的圖片(如用戶頭像)是圓形或者圓角矩形的,如果我們把每一種形狀的圖片都裁剪成一個圖片文件,這樣既麻煩也浪費空間,所以最好的辦法是通過代碼來設置圖片的顯示形狀。顯示圖片用到的是ImageView,最簡單的設置圖片形狀的方法就是在draw()裏面通過canvas.clipPath()把畫布裁剪成相應形狀,但這種方法有個很大的缺點,就是邊緣鋸齒明顯。
這裏我通過BitmapShader來繪製圖片,可以很好地解決鋸齒的問題,將畫筆的渲染器設置成BitmapShader,則通過畫筆繪製的圖案則以圖片爲背景。關鍵步驟爲:
// 獲取圖片
Bitmap bitmap = Util.getBitmapFromDrawable(getDrawable());
// 設置圖片渲染器
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// 把渲染器放入畫筆中
mBitmapPaint.setShader(mBitmapShader);
// 在畫布上畫圓,即可繪製出圓形圖片
canvas.drawCircle(cx, cy, radius, mBitmapPaint);
效果如下:
public class ShapeImageView extends ImageView {
public static int SHAPE_REC = 1; // 矩形
public static int SHAPE_CIRCLE = 2; // 圓形
public static int SHAPE_OVAL = 3; // 橢圓
private float mBorderSize = 0; // 邊框大小,默認爲0,即無邊框
private int mBorderColor = Color.WHITE; // 邊框顏色,默認爲白色
private int mShape = SHAPE_REC; // 形狀,默認爲直接矩形
private float mRoundRadius = 0; // 矩形的圓角半徑,默認爲0,即直角矩形
private Paint mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private RectF mViewRect = new RectF(); // imageview的矩形區域
private RectF mBorderRect = new RectF(); // 邊框的矩形區域
private final Matrix mShaderMatrix = new Matrix();
private Paint mBitmapPaint = new Paint();
private BitmapShader mBitmapShader;
private Bitmap mBitmap;
public ShapeImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ShapeImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); // 雖然此處會調用setImageDrawable,但此時成員變量還未被正確初始化
init(attrs);
mBorderPaint.setStyle(Style.STROKE);
mBorderPaint.setStrokeWidth(mBorderSize);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setAntiAlias(true);
mBitmapPaint.setAntiAlias(true);
super.setScaleType(ScaleType.CENTER_CROP); // 固定爲CENTER_CROP,其他不生效
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
mBitmap = Util.getBitmapFromDrawable(getDrawable());
setupBitmapShader();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = Util.getBitmapFromDrawable(drawable);
setupBitmapShader();
}
@Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != ScaleType.CENTER_CROP) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.ShapeImageView);
mShape = a.getInt(R.styleable.ShapeImageView_shape, mShape);
mRoundRadius = a.getDimension(R.styleable.ShapeImageView_round_radius, mRoundRadius);
mBorderSize = a.getDimension(R.styleable.ShapeImageView_border_size, mBorderSize);
mBorderColor = a.getColor(R.styleable.ShapeImageView_border_color, mBorderColor);
a.recycle();
}
/**
* 對於普通的view,在執行到onDraw()時,背景圖已繪製完成
* <p/>
* 對於ViewGroup,當它沒有背景時直接調用的是dispatchDraw()方法, 而繞過了draw()方法,
* 當它有背景的時候就調用draw()方法,而draw()方法裏包含了dispatchDraw()方法的調用,
*/
@Override
public void onDraw(Canvas canvas) {
if (getDrawable() != null) {
if (mShape == SHAPE_CIRCLE) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2,
Math.min(getWidth(), getHeight()) / 2, mBitmapPaint);
} else if (mShape == SHAPE_OVAL) {
canvas.drawOval(mViewRect, mBitmapPaint);
} else {
canvas.drawRoundRect(mViewRect, mRoundRadius, mRoundRadius, mBitmapPaint);
}
}
if (mBorderSize > 0) { // 繪製邊框
if (mShape == SHAPE_CIRCLE) {
canvas.drawCircle(mViewRect.right / 2, mViewRect.bottom / 2,
Math.min(mViewRect.right, mViewRect.bottom) / 2 - mBorderSize / 2, mBorderPaint);
} else if (mShape == SHAPE_OVAL) {
canvas.drawOval(mBorderRect, mBorderPaint);
} else {
canvas.drawRoundRect(mBorderRect, mRoundRadius, mRoundRadius, mBorderPaint);
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initRect();
setupBitmapShader();
}
// 不能在onLayout()調用invalidate(),否則導致繪製異常。(setupBitmapShader()中調用了invalidate())
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
// initRect();
// setupBitmapShader();
}
private void setupBitmapShader() {
// super(context, attrs, defStyle)調用setImageDrawable時,成員變量還未被正確初始化
if (mBitmapPaint == null) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setShader(mBitmapShader);
// 固定爲CENTER_CROP,使圖片在view中居中並裁剪
mShaderMatrix.set(null);
// 縮放到高或寬 與view的高或寬 匹配
float scale = Math.max(getWidth() * 1f / mBitmap.getWidth(), getHeight() * 1f / mBitmap.getHeight());
// 由於BitmapShader默認是從畫布的左上角開始繪製,所以把其平移到畫布中間,即居中
float dx = (getWidth() - mBitmap.getWidth() * scale) / 2;
float dy = (getHeight() - mBitmap.getHeight() * scale) / 2;
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate(dx, dy);
mBitmapShader.setLocalMatrix(mShaderMatrix);
invalidate();
}
// 設置圖片的繪製區域
private void initRect() {
mViewRect.top = 0;
mViewRect.left = 0;
mViewRect.right = getWidth(); // 寬度
mViewRect.bottom = getHeight(); // 高度
// 邊框的矩形區域不能等於ImageView的矩形區域,否則邊框的寬度只顯示了一半
mBorderRect.top = mBorderSize / 2;
mBorderRect.left = mBorderSize / 2;
mBorderRect.right = getWidth() - mBorderSize / 2;
mBorderRect.bottom = getHeight() - mBorderSize / 2;
}
public int getShape() {
return mShape;
}
public void setShape(int shape) {
mShape = shape;
}
public float getBorderSize() {
return mBorderSize;
}
public void setBorderSize(int mBorderSize) {
this.mBorderSize = mBorderSize;
mBorderPaint.setStrokeWidth(mBorderSize);
initRect();
invalidate();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(int mBorderColor) {
this.mBorderColor = mBorderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public float getRoundRadius() {
return mRoundRadius;
}
public void setRoundRadius(float mRoundRadius) {
this.mRoundRadius = mRoundRadius;
invalidate();
}
}
<declare-styleable name="ShapeImageView">
<attr name="shape" format="enum">
<enum name="rect" value="1"/>
<enum name="circle" value="2"/>
<enum name="oval" value="3"/>
</attr>
<attr name="round_radius" format="dimension"/>
<attr name="border_size" format="dimension"/>
<attr name="border_color" format="color"/>
</declare-styleable>