欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android中通過(guò)反射實(shí)現(xiàn)圓角ImageView代碼實(shí)例

 更新時(shí)間:2015年04月24日 11:28:12   投稿:junjie  
這篇文章主要介紹了Android中通過(guò)反射實(shí)現(xiàn)圓角ImageView代碼實(shí)例,本文直接給出核心實(shí)現(xiàn)代碼,需要的朋友可以參考下
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,在構(gòu)造方法中調(diào)用,初始化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);
  }

重寫(xiě)ImageView的onDraw方法,通過(guò)xfermode實(shí)現(xiàn)圓角

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();
      }
    }
  }

通過(guò)反射的方法將xfermode設(shè)置到BitmapDrawable 里面的內(nèi)部類(lèi)BitmapState里的對(duì)象mPaint,用來(lái)繪制圖片。

相關(guān)文章

最新評(píng)論