如何给自定义多边形view填充颜色

一下是我的多边形的代码
package com.example.bingyantest;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**

  • Created by HP on 2017/3/6.
  • 算法思想:每画出一条边旋转一次画布,最终旋转N次,画出N条边
  • 边的计算方法:利用多边形对应的外接园半径 R */

public class MyView extends View {

private Paint mpaint,npaint;
private float radius, start_x, start_y, end_x, end_y;
private float m = 30;
private float UNIT = 360 / m;
private float Xo,Yo;               //用于保存起始点的数据

public MyView(Context context) {
    this(context, null);
}

public MyView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    Log.d("222", "MyView: "+UNIT);
    mpaint = new Paint();
    npaint = new Paint();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    float mW = getMeasuredWidth();
    float mH = getMeasuredHeight();

    start_x = mW / 2;
    start_y = mH / 2;
    Xo = start_x;
    Yo = start_y;
    radius = Math.min(mW, mH) / 3;
}


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

    mpaint.setStyle(Paint.Style.STROKE);
    mpaint.setStrokeWidth(6);


    if (m > 24) {
        npaint.setColor(Color.RED);
        canvas.drawCircle(start_x,start_y,radius,npaint);
        canvas.drawCircle(start_x, start_y, radius, mpaint);
    } else {
        end_x = (float) (radius * Math.sin(Math.toRadians(UNIT)));
        end_x = start_x + end_x;
        end_y = (float) (radius * Math.cos(Math.toRadians(UNIT)));
        end_y = start_y - end_y;
        for (int i = 0; i < m; i++) {
            canvas.save();
            canvas.rotate(UNIT * i, start_x, start_y);

            canvas.drawLine(start_x, start_y - radius, end_x, end_y, mpaint);
            canvas.restore();
        }
    }
}

public void refresh(float m) {
    this.m = m;
    UNIT = 360 / this.m;
    invalidate();
}

}

1个回答

首先你是要给多边形的边框加上颜色还是多边形的内部填充上颜色。

如果是边框加上颜色。
mpaint.setStyle(Paint.Style.STROKE);
mpaint.setColor(Color.RED);

如果是给多变型填充颜色,
mpaint.setStyle(Paint.Style.FILL);
mpaint.setColor(Color.RED);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!