亲宝软件园·资讯

展开

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

人气:0
想了解Android中通过反射实现圆角ImageView代码实例的相关内容吗,在本文为您仔细讲解Android实现圆角ImageView的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,反射,圆角,ImageView,下面大家一起来学习吧。
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,用来绘制图片。

加载全部内容

相关教程
猜你喜欢
用户评论