zoukankan      html  css  js  c++  java
  • android开发之自定义圆形ImagView

    在日常使用中我们经常会使用到圆形的图片,但是android系统中并没有默认的圆形控件,所以我们需要自己来写一个自定义的ImagView来显示一张圆形的图片,下面先看效果

    详细的方法是我们自定义一个类,继承ImagView,然后重写一些方法,下面是代码
    /**
    * 圆形的ImagView
    *
    * @author Administrator
    *
    */
    public class RoundImageView extends ImageView {
    public RoundImageView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    }

    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) {

    Drawable drawable = getDrawable();

    if (drawable == null) {
    return;
    }

    if (getWidth() == 0 || getHeight() == 0) {
    return;
    }

    Bitmap b = ((BitmapDrawable) drawable).getBitmap();

    if (null == b) {
    return;
    }

    Bitmap bitmap = b.copy(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.5f,
    sbmp.getHeight() / 2 + 0.5f, sbmp.getWidth() / 2 + 0.5f, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(sbmp, rect, rect, paint);

    return output;
    }
    }
    然后在布局中引用这个自定义的控件, 就可以了
    <里面的是你的包名加自定义的类名,如果按住Ctrl+鼠标左键能进入类的话,就说明引用成功了。

    <comiptv.example.vincent.test.RoundImageView
    android:layout_centerInParent="true"
    android:src="@mipmap/a8"
    android:layout_width="300dp"
    android:layout_height="300dp"
    />
    这样就可以了
  • 相关阅读:
    CSUFT 1002 Robot Navigation
    CSUFT 1003 All Your Base
    Uva 1599 最佳路径
    Uva 10129 单词
    欧拉回路
    Uva 10305 给任务排序
    uva 816 Abbott的复仇
    Uva 1103 古代象形文字
    Uva 10118 免费糖果
    Uva 725 除法
  • 原文地址:https://www.cnblogs.com/android-blogs/p/5868122.html
Copyright © 2011-2022 走看看