Bitmap 基础:
位图:256位对比32位,存储信息量大但是占用内存也大, 图像质量较高。
ARGB:A=Alpha, R=Red, G=Green,B=BlueARGB_8888:8888意味着它们都用8个位来显示,32位的位图。
ARGB_4444:逻辑同上,16位的位图。
RGB_565:逻辑同上,16位的位图。
ALPHA_8:用8个位来表示透明度,8位的位图。
1.圆角实现方法一
自定义一个布局:
package com.example.shifulaile.util.circleimage;
public class CircleImage extends ImageView {
public CircleImage(Context context) {
super(context);
}
public CircleImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircleImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable)drawable).getBitmap() ;
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
Bitmap roundBitmap = getCroppedBitmap(bitmap, getWidth());
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
/*
* 对Bitmap裁剪,使其变成圆形,这步最关键 */
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if(bmp.getWidth() != radius || bmp.getHeight() != radius)
sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
else
sbmp = bmp;
Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(), Bitmap.Config.ARGB_8888);
final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(Color.parseColor("#BAB399"));
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
c.drawCircle(sbmp.getWidth() / 2+0.7f, sbmp.getHeight() / 2+0.7f, sbmp.getWidth() / 2+0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
c.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
加入到布局文件中:
<com.example.yuanimageview.CircleImage
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/headpic"/>
注意一定要是src,不能是background,在代码中设置的话 用img.setImageResource(R.drawable.headpic);
效果如图:
2. 方法二
/**
* @param x 图像的宽度
* @param y 图像的高度
* @param image 源图片
* @param outerRadiusRat 圆角的大小
* @return 圆角图片
*/
public Bitmap createFramedPhoto(int x, int y, Bitmap image, float outerRadiusRat) {
// 根据源文件新建一个darwable对象
Drawable imageDrawable = new BitmapDrawable(image);
// 新建一个新的输出图片
if (x <= 0 || y <= 0) return null;
Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
// 新建一个矩形
RectF outerRect = new RectF(0, 0, x, y);
// 产生一个红色的圆角矩形
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);
// 将源图片绘制到这个圆角矩形上
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
imageDrawable.setBounds(0, 0, x, y);
canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
imageDrawable.draw(canvas);
canvas.restore();
return output;
}
调用 imageview.setImageBitmap((Bitmap) output); 就可以实现给定角度的圆角。