Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中通過反射實現圓角ImageView代碼實例

Android中通過反射實現圓角ImageView代碼實例

編輯:關於Android編程

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,用來繪制圖片。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved