Android 개발 사용자 정의 컨트롤 의 접선 도 실현 방법 상세 설명

이 사례 는 안 드 로 이 드 개발 사용자 정의 컨트롤 의 접선 도 실현 방법 을 설명 한다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
머리말
접 는 선 도 는 안 드 로 이 드 개발 에서 흔히 볼 수 있 는 효과 이지 만 사용자 정의 View 에 관 한 지식 으로 입문 한 많은 소 백 들 에 게 깊 은 인상 을 줄 수 있다.사실은 그렇지 않다.그 다음 에 나 는 가능 한 한 통속 적 인 언어 로 다음 그림 의 접선 도 효과 의 실현 과정 을 설명 할 것 이다.
효과 도

실현 과정
우선 사용자 정의 컨트롤 방식 을 선택 하 십시오.
사용자 정의 컨트롤 의 실현 은 네 가지 방식 이 있 습 니 다.
1.View 를 계승 하고 onDraw,onMeasure 등 을 다시 쓰 는 방법.
2.기 존의 View(예 를 들 어 TextView)를 계승 합 니 다.
3.ViewGroup 을 계승 하여 사용자 정의 레이아웃 을 구현 합 니 다.
4.기 존의 ViewGroup(예 를 들 어 LinearLayout)을 계승 합 니 다.
여러 개의 컨트롤 을 조합 할 필요 도 없고 기 존의 컨트롤 을 바탕 으로 개조 할 필요 도 없 기 때문에 우 리 는 첫 번 째 방식 으로 View 를 계승 하여 실현 합 니 다.코드 는 다음 과 같 습 니 다.ChartView 류 를 새로 만 들 고 View 에서 계승 하 며 그의 몇 가지 구조 방법 을 실현 합 니 다.그리고 onDraw 와 onMeasure 방법 을 다시 씁 니 다.왜냐하면 우 리 는 onDraw 방법 에서 그리 기 작업 을 해 야 하고 이 컨트롤 의 길이 와 너비 가 같 기 를 바 랍 니 다.그래서 onMeasure 방법 에 너비 와 높이 가 같 습 니 다.길이 와 너비 가 같은 방식 을 설정 하 는 것 은 매우 간단 합 니 다.우 리 는 스스로 측정 하여 실현 할 필요 가 없습니다.부모 류 의 onMeasure 방법 을 사용 하면 매개 변수(너비 와 높이)를 전달 할 때 모두 너비(또는 높이)로 전달 하면 됩 니 다.

public class ChartView extends View {

  public ChartView(Context context) {
    super(context);
  }

  public ChartView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
  }

  public ChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
  }
}

그 다음 에 간단 한 도형 을 그 려 서 표시 합 니 다.
그림 을 그리 기 전에 우 리 는 붓 의 초기 화 를 포함 하여 약간의 초기 화 작업 을 해 야 한다.그 다음 에 그림 을 그 릴 수 있 습 니 다.우 리 는 먼저 간단 한 원 을 그 린 다음 에 컨트롤 을 레이아웃 파일 에 넣 고 효 과 를 실행 할 수 있 습 니 다.
ChartView 코드

public class ChartView extends View {

  //   
  private Paint paint;

  /**
  *     
  */
  public ChartView(Context context) {
    super(context);
    initWork();
  }

  /**
  *     
  */
  public ChartView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    initWork();
  }

  /**
  *     
  */
  public ChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initWork();
  }

  /**
  *      
  */
  private void initWork() {
    initPaint();
  }

  /**
  *     
  */
  private void initPaint() {
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //        
    paint.setStyle(Paint.Style.FILL);
    //       
    paint.setColor(Color.RED);
    //    3  
    paint.setStrokeWidth(3);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //   
    canvas.drawCircle(300,300,100,paint);
  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"

  <com.toprs.linechart.ChartView
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

효과:

그리고 도 표를 그립 니 다.
지금까지 가장 간단 한 사용자 정의 컨트롤 이 실현 되 었 습 니 다.아무 기능 도 없 지만 빨간색 원 을 간단하게 표시 할 뿐 본질 은 똑 같 습 니 다.다음은 도표 작성 을 시작 하 겠 습 니 다.
1.사용 할 값 을 초기 화 합 니 다.

  //        
  private int degreeSpace;


  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //                 (      !)
    int left = getLeft();
    int right = getRight();
    int top = getTop();
    int bottom = getBottom();
    int w = getWidth();

    //            
    int graphPadding = w / 10;
    //         
    int graphLeft = left + graphPadding;
    int graphBottom = bottom - graphPadding;
    int graphRight = right - graphPadding;
    int graphTop = top + graphPadding;
    //     (      ~)
    int graphW = graphRight - graphLeft;
    //        
    degreeSpace = graphW / 8;
  }

2.회색 배경

  //   
  canvas.drawColor(Color.LTGRAY);

3.좌표계

  //        STROKE  ,       
  paint.setStyle(Paint.Style.STROKE);

  //      
  Path pivotPath = new Path();
  //Y 
  pivotPath.moveTo(graphLeft, graphBottom);
  pivotPath.lineTo(graphLeft, graphTop);
  //Y   
  pivotPath.lineTo(graphLeft - 12, graphTop + 20);
  pivotPath.moveTo(graphLeft, graphTop);
  pivotPath.lineTo(graphLeft + 12, graphTop + 20);
  //X 
  pivotPath.moveTo(graphLeft, graphBottom);
  pivotPath.lineTo(graphRight, graphBottom);
  //X   
  pivotPath.lineTo(graphRight - 20, graphBottom + 12);
  pivotPath.moveTo(graphRight, graphBottom);
  pivotPath.lineTo(graphRight - 20, graphBottom - 12);
  canvas.drawPath(pivotPath, paint);

4.눈금 점선 및 숫자

  // Y     
  for (int i = 1; i < 8; i++) {
    Path yKeduPath = new Path();
    //  
    paint.setColor(Color.WHITE);
    paint.setStrokeWidth(1);
    paint.setStyle(Paint.Style.STROKE);
    paint.setPathEffect(new DashPathEffect(new float[]{5,5},0));
    yKeduPath.moveTo(graphLeft, graphBottom - i * degreeSpace);
    yKeduPath.lineTo(graphRight, graphBottom - i * degreeSpace);
    canvas.drawPath(yKeduPath, paint);
    //   
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.FILL);
    paint.setTextSize(25);
    paint.setPathEffect(null);
    canvas.drawText(i + "", graphPadding / 2, graphBottom - i * degreeSpace, paint);
  }
  // X     
  for (int i = 1; i < 8; i++) {
    Path xKeduPath = new Path();
    //  
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(1);
    paint.setPathEffect(new DashPathEffect(new float[]{5,5},0));
    xKeduPath.moveTo(graphLeft + i * degreeSpace, graphBottom);
    xKeduPath.lineTo(graphLeft + i * degreeSpace, graphTop);
    canvas.drawPath(xKeduPath, paint);
    //   
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.FILL);
    paint.setTextSize(25);
    paint.setPathEffect(null);
    canvas.drawText(i + "", graphLeft + i * degreeSpace, graphBottom + graphPadding / 2, paint);
  }

5.접선
접 는 선 을 그리 기 전에,우 리 는 먼저 몇 개의 인 자 를 초기 화해 야 한다.

  //     
  private float[] data = {3.2f, 4.3f, 2.5f, 3.2f, 3.8f, 7.1f, 1.3f, 5.6f};
  //          
  private int showNum=1;


  //   
  Path linePath = new Path();
  for (int i = 0; i < showNum; i++) {
    int toPointX = graphLeft + i * degreeSpace;
    int toPointY = graphBottom - ((int) (data[i] * degreeSpace));
    paint.setColor(Color.YELLOW);
    paint.setStyle(Paint.Style.STROKE);
    if (i==0){
      linePath.moveTo(toPointX,toPointY);
    }else {
      linePath.lineTo(toPointX, toPointY);
    }
    //     
    canvas.drawCircle(toPointX, toPointY,10,paint);
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawCircle(toPointX,toPointY,7,paint);
  }
  paint.setColor(Color.YELLOW);
  paint.setStyle(Paint.Style.STROKE);
  paint.setStrokeWidth(3);
  canvas.drawPath(linePath, paint);

6.그래프 를 움 직 여 라
데이터 가 순서대로 나타 나 는 애니메이션 을 실현 하기 위해 서 우 리 는 현재 표 시 된 데이터 수량 인 showNum 변수 가 계속 1 을 추가 하고 0.5 초 간격 으로 스 레 드 를 엽 니 다.그리고 post Invalidate()를 다시 그리 면 됩 니 다.

  private void initWork() {
    initPaint(); 
    //     ,  0.5 showNum  
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (true){
          if (showNum<data.length){
            showNum++;
          }else {
            showNum=1;
          }
          //   
          postInvalidate();
          //   0.5 
          try {
            Thread.sleep(500);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }

자,운행 하면 위의 효 과 를 실현 할 수 있 습 니 다.시 크 함 이 부족 하거나 기능 이 부족 하 다 고 생각 되면 스스로 보완 하 세 요~
결어
사용자 정의 컨트롤 은 안 드 로 이 드 진급 로 에서 반드시 만 나 야 할 지식 이기 때문에 중시 하 시기 바 랍 니 다.사실 사용자 정의 컨트롤 은 어렵 고 간단 하 다.일반적인 효 과 를 실현 하 는 것 은 매우 편리 하 다.이번 예 와 같이 각종 시 크 한 효 과 를 실현 하고 각종 기능 을 보완 하려 면 수학,물리,그림 그리 기 등 지식 을 포함 한 각종 지식의 배합 이 필요 하 다.그래서 평소에 쌓 아 온 것 이 필요 합 니 다.다른 사람의 컨트롤 이 좋 을 때 자신 이 실현 해 볼 수 있 습 니 다.자신의 지식 고 를 계속 보충 하면 자 연 스 럽 게 능숙 하 게 활용 할 수 있 습 니 다.본인 도 풋내기 입 니 다.함께 격려 하 세 요!!
더 많은 안 드 로 이 드 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.
본 고 에서 말 한 것 이 여러분 의 안 드 로 이 드 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기