Android 图片圆角实现方法
程序员文章站
2022-06-17 15:47:16
...
效果:圆角,圆形,椭圆形
实现方法:
工具方法
/**
* 设置BitmapShader
*/
private void setBitmapShader() {
Drawable drawable = getDrawable();
if (null == drawable) {
return;
}
Bitmap bitmap = drawableToBitmap(drawable);
// 将bitmap作为着色器来创建一个BitmapShader
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale = 1.0f;
if (mType == TYPE_CIRCLE) {
// 拿到bitmap宽或高的小值
int bSize = Math.min(bitmap.getWidth(), bitmap.getHeight());
scale = mWidth * 1.0f / bSize;
} else if (mType == TYPE_ROUND || mType == TYPE_OVAL) {
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(), getHeight() * 1.0f / bitmap.getHeight());
}
// shader的变换矩阵,我们这里主要用于放大或者缩小
mMatrix.setScale(scale, scale);
// 设置变换矩阵
mBitmapShader.setLocalMatrix(mMatrix);
mPaint.setShader(mBitmapShader);
}
/**
* drawable转bitmap
*
* @param drawable
* @return
*/
private Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
return bitmapDrawable.getBitmap();
}
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
绘制方法
@Override
protected void onDraw(Canvas canvas) {
if (null == getDrawable()) {
return;
}
setBitmapShader();
if (mType == TYPE_CIRCLE) {
canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
} else if (mType == TYPE_ROUND) {
mPaint.setColor(Color.RED);
canvas.drawRoundRect(mRect, mRoundRadius, mRoundRadius, mPaint);
}else if(mType == TYPE_OVAL){
canvas.drawOval(mRect, mPaint);
}
}
demo地址:https://download.csdn.net/download/meixi_android/11896635
demo云盘:https://pan.baidu.com/s/1c6Crvgd0rHWChtjfkjWJag&shfl=sharepset
在线bug交流:QQ1085220040
上一篇: zend开发工具解决思路