안 드 로 이 드 가 원형 그림 을 그 리 는 두 가지 방식 의 예제

안 드 로 이 드 가 원형 그림 을 그 리 는 두 가지 방식
일단 효 과 를 보고...


다음은 완전한 예제 코드 가 있다.
BitmapShader 사용 하기(착색 기)
우리 가 view 를 그 릴 때 초등학교 미술 시간 에 물 색 연필 로 공책 에 그림 을 그리고 착색 기 를 사용 하여 원형 그림 을 그 리 는 가장 쉬 운 이해 방식 은 바로 bitmap 를 하나의 색깔 로 paint 에 설정 하 는 것 이다.paint 는 이미 색깔 이 있 으 니 네가 원 하 는 곳,원,납작 해 지 는 것 은 네 마음 을 보 는 것 이 아니 라 canvas 가 그 방법 을 사용 하 는 것 이다.
실현 의 대체적인 사고방식 은 다음 과 같다.
1.계승 imageView 재 작성 onDraw()클래스 만 들 기
2.bitmap 그림 가 져 오기
3.그림 의 크기 조정 비율 을 계산 하려 면 행렬 matrix 를 사용 하여 크기 를 조정 합 니 다.
4.BitmapShader 착색 기 만 들 기
5.paint 설정 착색 기 그리 기
구체 적 으로 주석 을 실현 하 는 것 도 명확 하 게 표시 되 어 있다.

  private void shaderCircle(Canvas canvas){
    //  Drawable
    Drawable resources=getDrawable();
    float scale = 1.0f;//    
    int mRadius=0;//    
    if (resources instanceof BitmapDrawable){
      //  bitmap
      Bitmap bitmap=((BitmapDrawable) resources).getBitmap();
      if (bitmap==null) return;
      //   bitmap      
      int minBitMap = Math.min(bitmap.getWidth(), bitmap.getHeight());
      // view                  
      int minValue=Math.min(getWidth(),getHeight());
      //    
      mRadius=minValue/2;
      //          *1.0f   int            0 1        
      scale=minValue*1.0f/minBitMap;
      //      
      matrix.setScale(scale,scale);
      /**
       *             
       * TileMode      :
       * CLAMP    REPEAT     MIRROR   
       */
      BitmapShader shader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
      //    
      shader.setLocalMatrix(matrix);
      paint.setShader(shader);
      canvas.drawCircle(mRadius, mRadius, mRadius, paint);
    }
  }
Xfermode 를 사용 하여 그림 교차 모드 를 설정 합 니 다.
쉽게 말 하면 한 장의 캔버스 에 두 장의 그림 을 그 렸 는데 이 두 장의 그림 은 어떤 방식 으로 표 시 됩 니까?예 를 들 어 상층 사진 만 표시 하고 하층 사진 만 표시 하 며 두 장의 교차 부분 을 표시 하 는 등 입 니 다.
사고의 방향 을 실현 하 다.
1.빈 bitmap 을 만 듭 니 다.이 bitmap 에 따라 Canvas 를 만 듭 니 다.
2.캔버스 투명 을 설정 해서 원 하 는 모양 으로 그리 기
3.도형 교차 모드 설정
4.캔버스 에 그림 자원 가 져 오기
구현 코드

 private Bitmap getCircleBitmap(){
    Drawable drawable=getDrawable();

    if (drawable instanceof BitmapDrawable) {
      Paint paint=new Paint();
      paint.setAntiAlias(true);
      //      
      Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
      //     
      Bitmap output=Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
      //    
      Canvas canvas=new Canvas(output);
      //         
      canvas.drawColor(Color.TRANSPARENT);
      paint.setColor(Color.WHITE);
      //      
      if (type==ROUND){
        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRound, mRound,paint);
      }else{
        //      
      
        // view                  
        int minValue = Math.min(getWidth(), getHeight());
        //    
        mRadius = minValue / 2;
        canvas.drawCircle(mRadius,mRadius,mRadius,paint);
      }
      //        
      paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

      Rect src=new Rect(0,0,bitmap.getWidth(),bitmap.getHeight());
      Rect dst=new Rect(0,0,output.getWidth(),output.getHeight());
      canvas.drawBitmap(bitmap,src,dst,paint);
      return output;
    }
    return null;

  }

이 아주 전형 적 인 그림...

PorterDuff.Mode.CLEAR        
PorterDuff.Mode.SRC       
PorterDuff.Mode.DST       
PorterDuff.Mode.SRC_OVER        ,      
PorterDuff.Mode.DST_OVER       ,      
PorterDuff.Mode.SRC_IN                 
PorterDuff.Mode.DST_IN          ,       
PorterDuff.Mode.SRC_OUT           
PorterDuff.Mode.DST_OUT           
PorterDuff.Mode.SRC_ATOP                    
PorterDuff.Mode.DST_ATOP                    
PorterDuff.Mode.XOR            
참고 문서
ImageVIEW 를 계승 하여 원형 과 원 각 이미지 컨트롤 을 완성 하 는 과정(착색 기 사용)

  <declare-styleable name="CircleImage">
    <attr name="imageRound" format="dimension"/>
    <attr name="imageType">
      <enum name="circle" value="0"/>
      <enum name="round" value="1"/>
    </attr>

  </declare-styleable>

public class CircleImage extends ImageView {

  private Matrix matrix;
  private Paint paint;
  private int mRound;//    
  private int mRadius;//    
  private int type;//    
  private final int CIRCLE=0;//  
  private final int ROUND=1;//  

  public CircleImage(Context context) {
    super(context,null);
  }

  public CircleImage(Context context, AttributeSet attrs) {
    super(context, attrs);
    matrix=new Matrix();
    paint=new Paint();
    paint.setAntiAlias(true);
    initAttrValues(context,attrs);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    if (getDrawable() == null) {
      return;
    }
    setShader();
    if (type==CIRCLE){
      canvas.drawCircle(mRadius, mRadius, mRadius, paint);
    }else{
      canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRound, mRound,paint);
    }
  }

  /**
   *        
   * @param context
   * @param attrs
   */
  private void initAttrValues(Context context, AttributeSet attrs){
    TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.CircleImage);
    for (int i=0;i<typedArray.getIndexCount();i++){
      int index=typedArray.getIndex(i);
      switch (index){
        case R.styleable.CircleImage_imageRound:
          mRound =typedArray.getDimensionPixelSize(index,
              (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10,getResources().getDisplayMetrics()));
          break;
        case R.styleable.CircleImage_imageType:
          type=typedArray.getInt(index,CIRCLE);
          break;
      }
    }
  }

  /**
   *      
   */
  private void setShader() {
    //  Drawable
    Drawable resources=getDrawable();
    float scale = 1.0f;//    
    if (resources instanceof BitmapDrawable) {
      //  bitmap
      Bitmap bitmap = ((BitmapDrawable) resources).getBitmap();
      if (bitmap == null) return;
      //  
      if (type==CIRCLE){
        //   bitmap      
        int minBitMap = Math.min(bitmap.getWidth(), bitmap.getHeight());
        // view                  
        int minValue = Math.min(getWidth(), getHeight());
        //    
        mRadius = minValue / 2;
        //          *1.0f   int            0 1        
        scale = minValue * 1.0f / minBitMap;
      }else{
        //  view                    view
        scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(), getHeight()
            * 1.0f / bitmap.getHeight());
      }
      //      
      matrix.setScale(scale, scale);
      /**
       *             
       * TileMode      :
       * CLAMP    REPEAT     MIRROR   
       */
      BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
      //    
      shader.setLocalMatrix(matrix);
      //    
      paint.setShader(shader);
    }
  }


  /**
   *                  
   * @param event
   * @return
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction()==MotionEvent.ACTION_DOWN){
      if (type==CIRCLE){
        mRound =10;
        type=ROUND;
      }else{
        type=CIRCLE;
      }
      invalidate();
    }
    return super.onTouchEvent(event);
  }
}

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기