发现一个奇怪现象:
SDK Manager里API16的是版本4.1.2 却没有4.1.1的(是因为4.1.1的版本有bug吗?)
GenyMotion模拟器里没有4.1.2版本的,只有4.1.1的。。。
Samsung Galaxy Note 4.1.1 API16里显示不了圆角图片,Eclipse里的布局预览API16 4.1.2里都是正常的。
如上图所示,4.1.1版本的始终变不了圆形的图片。(实际上自己的手机小辣椒Q1也是4.1.1版本的,跟上面一样,变不了圆形图片)。中间那一张图片用的是官方的模拟器,4.1.2版本的(没有4.1.1的)。
代码如下: 图片要放在src属性上(background属性无效)
public class RoundImageView extends ImageView {
Path mPath = new Path();
public RoundImageView(Context context) {
super(context);
}
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
<u>mPath.addCircle(width/2, height/2, height/2, Direction.CW);
canvas.clipPath(mPath);</u>
super.onDraw(canvas);
}
}
但是有很明星的锯齿。。。
换成下面一种方法可以实现抗锯齿了,4.1.1版本的也没有问题了, 但是感觉要消耗更多的资源。
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable==null || getWidth()==0 || getHeight()==0) {
return;
}
Bitmap b = ((BitmapDrawable)drawable).getBitmap();
canvas.drawBitmap(getRoundedBitmap(b), 0, 0, null);
}
public static Bitmap getRoundedBitmap(Bitmap bitmap){
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getHeight()/2, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}