2012-09-28 2 views
3

xml 레이아웃을 기반으로하는 사용자 정의보기를 만들었습니다. 보기를 지울 수있는 단추를 추가했습니다. 이제 클릭 할 때 캔버스 영역을 비우고 싶습니다. xml 레이아웃 file.Now에서 onClick 이벤트를 추가하여 전체보기/캔버스를 지우는 코드를 어디에 추가합니까? 몇 가지 코드를 추가했습니다. (이것은 아무것도 지우지 않습니다). 내 활동,보기 및 레이아웃 파일을 아래 순서대로 추가했습니다.캔버스 영역 지우기

public class CustomViewActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    } 

    public void clearLine(View v) { 

    new CustomView(CustomViewActivity.this, null).clearCanvas();   
    } 

} 

public class CustomView extends View { 

    private Paint paint = new Paint(); 
     private Path path = new Path(); 
     public Boolean clearCanvas = false; 

     public CustomView(Context context, AttributeSet attrs, int defStyle) { 
      super(context, attrs, defStyle);   
     } 

    public CustomView(Context context,AttributeSet attrs) { 
     super(context,attrs); 
     paint.setAntiAlias(true); 
     paint.setColor(Color.BLUE); 
     paint.setTextSize(20); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeJoin(Paint.Join.ROUND); 
     paint.setStrokeWidth(5f); 
    } 

    protected void onDraw(Canvas canvas) { 
    if(clearCanvas) 
     { // Choose the colour you want to clear with. 
      canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); 
      //canvas.drawColor(0, Mode.CLEAR); 
      clearCanvas = false;    
     } 

     super.onDraw(canvas); 
     canvas.drawText("Hello World", 5, 30, paint); 
     canvas.drawPath(path, paint); 

    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

    //int action = event.getAction() & MotionEvent.ACTION_MASK; 

     float eventX = event.getX(); 
     float eventY = event.getY(); 

     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
      path.moveTo(eventX, eventY); 

      return true; 
      case MotionEvent.ACTION_MOVE: 
      path.lineTo(eventX, eventY); 
      break; 
      case MotionEvent.ACTION_UP: 
      // nothing to do 
      break; 
      default: 
      return false; 
     } 

     // Schedules a repaint. 
     invalidate(); 
     return true; 

    } 
    public void clearCanvas(){ 

      clearCanvas = true; 
      postInvalidate(); 
      //canvas.drawColor(0, Mode.CLEAR); 

     } 

} 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 


      <com.example.CustomViewEvent.CustomView 
       android:id="@+id/customView" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" /> 

      <Button 
       android:id="@+id/button1" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentBottom="true" 
       android:layout_centerHorizontal="true" 
       android:layout_marginBottom="28dp" 
       android:onClick="clearLine" 
       android:text="CLEAR" /> 

</RelativeLayout> 
+0

drawColor가 나에게 좋은 출발 인 것 같습니다. – njzk2

답변

5

수행해야 할 작업은 onDraw 메소드에서 캔버스에 액세스하는 것입니다.

그래서 전역 변수를 사용하는 경우 버튼 클릭 방법에서 true로 설정하십시오. OnDraw에서 상태를 확인하고 필요한 경우 캔버스를 지울 수 있습니다. (그런 다음 매번 다시하지 않으므로 false로 설정하십시오.)

사용법은 아래 코드를 참조하십시오.

public Boolean clearCanvas = false; 

protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     if(clearCanvas) 
     { // Choose the colour you want to clear with. 
      canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); 
      clearCanvas = false; 
     } 
     canvas.drawPath(path, paint);  
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

    float eventX = event.getX(); 
     float eventY = event.getY(); 

     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
      path.moveTo(eventX, eventY); 

      return true; 
      case MotionEvent.ACTION_MOVE: 
      path.lineTo(eventX, eventY); 
      break; 
      case MotionEvent.ACTION_UP: 
      // nothing to do 
      break; 
      default: 
      return false; 
     } 

     // Schedules a repaint. 
     invalidate(); 
     return true; 

    } 
// this is the method which will be invoked from main activity class for clearing whatever //is in the view/canvas 
     public void clearCanvas(){ 

      //canvas.drawColor(0, Mode.CLEAR); 

      clearCanvas = true; 
      invalidate(); 
     } 

} 

편집 : 새 코드를 보면 나는 몇 가지 문제를 참조하십시오.

나는 올바른보기를 지우지 않고 있다는 사실을 돌이켜 생각합니다.

먼저 기존보기의 인스턴스를 가져옵니다. 그럼 당신은 그것을 지울 수 있습니다. 그것의 존재하지 않는 잘못된 인스턴스보다는 오히려.

CustomView cv = (CustomView)findViewById(R.id.customView); 
cv.clearCanvas(); 

invalidate(); 다른 postInvalidate(); 하나는 작동합니다보십시오.

postInvalidate()은 UI가 아닌 스레드에서 실행되는 경우입니다.

+0

PorterDuff in PorterDuff.Mode.CLEAR); 오류가 발생했습니다. 이 PorterDuff은 무엇입니까? – Tanvir

+0

나는이 새로운 CustomView (CustomViewActivity.isis, null) .clearCanvas()에 의해 activity-onclik 메서드에서 method-clearCanvas()를 호출했다. 아직 invalidate()를 호출 할 때 onDraw()를 다시 호출하지 않습니다. \t \t } – Tanvir

+0

당신은'postInvalidate()'를 시도 할 수 있습니다. 그것이 유효한 경우에만'Mode.CLEAR'를 사용하십시오. 당신의 구조가 어떤 것인지 모르겠지만, 제 onDraw는 게임 루프에서 호출됩니다. 무효화가 작동하지 않는다는 사실은 또 하나의 질문입니다. 새로운 답변을 열면 더 좋은 답변을 얻을 수 있습니다. – Doomsknight