欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中通过反射实现圆角ImageView代码实例

程序员文章站 2022-06-23 10:15:15
private void init(){ paint = new paint(paint.anti_alias_flag); round...
private void init(){
    paint = new paint(paint.anti_alias_flag);    
    roundrect = new rectf(0, 0, getwidth() , getheight());
    radius = 40;
    mporterduffxfermode = new porterduffxfermode(porterduff.mode.src_in) ;
  }

继承imageview,在构造方法中调用,初始化paint和xfermode。

 protected void ondraw(canvas canvas) {    
    int sc = canvas.savelayer(0, 0, getwidth() , getheight(), null,
        canvas.matrix_save_flag |
        canvas.clip_save_flag |
        canvas.has_alpha_layer_save_flag |
        canvas.full_color_layer_save_flag |
        canvas.clip_to_layer_save_flag);    
    roundrect.set(0, 0, getwidth(), getheight());
    canvas.drawroundrect(roundrect, radius, radius, paint);    
    reflectsetxfermod();    
    super.ondraw(canvas);    
    canvas.restoretocount(sc);
  }

重写imageview的ondraw方法,通过xfermode实现圆角

private void reflectsetxfermod(){
    drawable drawable = getdrawable();
    if(drawable == null){
      return;
    }    
    
    class bsclass = null;
    class[] innerclasses = bitmapdrawable.class.getdeclaredclasses();
    for(class innerclass :innerclasses)
    {
      string name = innerclass.getname();
      system.out.println("-----innerclass---"+name);
      if(name.equals("android.graphics.drawable.bitmapdrawable$bitmapstate"))
      {
        bsclass = innerclass;
      }      
    }
    
    if(bsclass!= null){      
      try {
        field mpaintfield = bsclass.getdeclaredfield("mpaint");
        mpaintfield.setaccessible(true);
        constantstate constantstate = ((bitmapdrawable)drawable).getconstantstate();
        paint paint = (paint)mpaintfield.get(constantstate);
        paint.setxfermode(mporterduffxfermode);
      } catch (illegalargumentexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      } catch (illegalaccessexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      } catch (nosuchfieldexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
    }
  }

通过反射的方法将xfermode设置到bitmapdrawable 里面的内部类bitmapstate里的对象mpaint,用来绘制图片。