您的位置:首页 > 其它

一个非常好用的自定义圆形控件

2016-06-29 19:28 525 查看
现在我们在开发中,不难发现,那些四方四正的图片渐渐的被圆形圆角所替代,那么我们怎么怎么才能让Android中的ImageView实现圆形与圆角的图片呢?我们知道,Android自己的ImageView并不可以实现圆形圆角图片的,那我们想要圆形与圆角的图片该怎么做呢???

这里我所知道的有两种办法:

1、ImageLoader可以一行代码实现Android圆形圆角图片的;

2、如果不用第三方框架的话,那么只能自定义控件了,这里推荐一个自定义的控件,然后我们布局中直接使用就可以实现圆形图片了。

我还是直接上代码吧:

package com.bawei.shop.view;

/**
* Created by ThinkPad on 2016/6/8.
* 自定义图片的圆形
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundImageView extends ImageView {

private Bitmap b;

public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public RoundImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {

Drawable drawable = getDrawable();

if (drawable == null) {
return;
}

if (getWidth() == 0 || getHeight() == 0) {
return;
}
if (drawable instanceof BitmapDrawable) {
b = ((BitmapDrawable) drawable).getBitmap();
}
// b = ((BitmapDrawable) drawable).getBitmap();

if (null == b) {
return;
}

Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

int w = getWidth(), h = getHeight();

Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);

}

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(),
Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f,
sbmp.getHeight() / 2 + 0.7f, sbmp.getWidth() / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);

return output;
}
}
那么我们现在有了这个RoudImageView,我们该怎么用呢?很简单,布局中直接用就是!

希望对大家有所帮助哦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: