Android 프로 그래 밍 은 canvas 가 떡 모양 통계 도 를 그 리 는 기능 예제[항목 의 수량 과 크기 에 자동 으로 적응]를 실현 합 니 다.
본 사례 의 목적 은 간단 한 떡 모양 통계 도 를 실현 하 는 것 이 고 효 과 는 다음 과 같다.
특징:
1.사용 이 매우 편리 합 니 다.xml 레이아웃 파일 에 넣 고 코드 에 내용 을 설정 할 수 있 습 니 다.즉,:
PieChartView pieChartView = (PieChartView) findViewById(R.id.pie_chart);
PieChartView.PieItemBean[] items = new PieChartView.PieItemBean[]{
new PieChartView.PieItemBean(" ", 200),
new PieChartView.PieItemBean(" ", 100),
new PieChartView.PieItemBean(" ", 120),
new PieChartView.PieItemBean(" ", 160),
new PieChartView.PieItemBean(" ", 100),
new PieChartView.PieItemBean(" ", 480)
};
pieChartView.setPieItems(items);
2.항목 의 수량,크기 와 접 는 위치,길이 가 모두 적응 합 니 다.왼쪽 항목 은 왼쪽으로 선 을 긋 고 오른쪽 항목 은 오른쪽으로 선 을 긋 습 니 다.문자 설명 과 백분율 이 가운데 로 정렬 되 고 문자'밑줄'과 문자 길이 가 적응 합 니 다.아주 작은 항목 에 대해 서 는 문자 가 가 려 지지 않도록 자동 으로 접 는 선 을 연장 합 니 다.핵심 코드:PieChartView.Java:
public class PieChartView extends View {
private int screenW, screenH;
/**
* The paint to draw text, pie and line.
*/
private Paint textPaint, piePaint, linePaint;
/**
* The center and the radius of the pie.
*/
private int pieCenterX, pieCenterY, pieRadius;
/**
* The oval to draw the oval in.
*/
private RectF pieOval;
private float smallMargin;
private int[] mPieColors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.MAGENTA, Color.CYAN};
private PieItemBean[] mPieItems;
private float totalValue;
public PieChartView(Context context) {
super(context);
init(context);
}
public PieChartView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PieChartView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
//init screen
screenW = ScreenUtils.getScreenW(context);
screenH = ScreenUtils.getScreenH(context);
pieCenterX = screenW / 2;
pieCenterY = screenH / 3;
pieRadius = screenW / 4;
smallMargin = ScreenUtils.dp2px(context, 5);
pieOval = new RectF();
pieOval.left = pieCenterX - pieRadius;
pieOval.top = pieCenterY - pieRadius;
pieOval.right = pieCenterX + pieRadius;
pieOval.bottom = pieCenterY + pieRadius;
//The paint to draw text.
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(ScreenUtils.dp2px(context, 16));
//The paint to draw circle.
piePaint = new Paint();
piePaint.setAntiAlias(true);
piePaint.setStyle(Paint.Style.FILL);
//The paint to draw line to show the concrete text
linePaint = new Paint();
linePaint.setAntiAlias(true);
linePaint.setStrokeWidth(ScreenUtils.dp2px(context, 1));
}
//The degree position of the last item arc's center.
private float lastDegree = 0;
//The count of the continues 'small' item.
private int addTimes = 0;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mPieItems != null && mPieItems.length > 0) {
float start = 0.0f;
for (int i = 0; i < mPieItems.length; i++) {
//draw pie
piePaint.setColor(mPieColors[i % mPieColors.length]);
float sweep = mPieItems[i].getItemValue() / totalValue * 360;
canvas.drawArc(pieOval, start, sweep, true, piePaint);
//draw line away from the pie
float radians = (float) ((start + sweep / 2) / 180 * Math.PI);
float lineStartX = pieCenterX + pieRadius * 0.7f * (float) (Math.cos(radians));
float lineStartY = pieCenterY + pieRadius * 0.7f * (float) (Math.sin(radians));
float lineStopX, lineStopY;
float rate;
if (getOffset(start + sweep / 2) > 60) {
rate = 1.3f;
} else if (getOffset(start + sweep / 2) > 30) {
rate = 1.2f;
} else {
rate = 1.1f;
}
//If the item is very small, make the text further away from the pie to avoid being hided by other text.
if (start + sweep / 2 - lastDegree < 30) {
addTimes++;
rate += 0.2f * addTimes;
} else {
addTimes = 0;
}
lineStopX = pieCenterX + pieRadius * rate * (float) (Math.cos(radians));
lineStopY = pieCenterY + pieRadius * rate * (float) (Math.sin(radians));
canvas.drawLine(lineStartX, lineStartY, lineStopX, lineStopY, linePaint);
//write text
String itemTypeText = mPieItems[i].getItemType();
String itemPercentText = Utility.formatFloat(mPieItems[i].getItemValue() / totalValue * 100) + "%";
float itemTypeTextLen = textPaint.measureText(itemTypeText);
float itemPercentTextLen = textPaint.measureText(itemPercentText);
float lineTextWidth = Math.max(itemTypeTextLen, itemPercentTextLen);
float textStartX = lineStopX;
float textStartY = lineStopY - smallMargin;
float percentStartX = lineStopX;
float percentStartY = lineStopY + textPaint.getTextSize();
if (lineStartX > pieCenterX) {
textStartX += (smallMargin + Math.abs(itemTypeTextLen - lineTextWidth) / 2);
percentStartX += (smallMargin + Math.abs(itemPercentTextLen - lineTextWidth) / 2);
} else {
textStartX -= (smallMargin + lineTextWidth - Math.abs(itemTypeTextLen - lineTextWidth) / 2);
percentStartX -= (smallMargin + lineTextWidth - Math.abs(itemPercentTextLen - lineTextWidth) / 2);
}
canvas.drawText(itemTypeText, textStartX, textStartY, textPaint);
//draw percent text
canvas.drawText(itemPercentText, percentStartX, percentStartY, textPaint);
//draw text underline
float textLineStopX = lineStopX;
if (lineStartX > pieCenterX) {
textLineStopX += (lineTextWidth + smallMargin * 2);
} else {
textLineStopX -= (lineTextWidth + smallMargin * 2);
}
canvas.drawLine(lineStopX, lineStopY, textLineStopX, lineStopY, linePaint);
lastDegree = start + sweep / 2;
start += sweep;
}
}
}
public PieItemBean[] getPieItems() {
return mPieItems;
}
public void setPieItems(PieItemBean[] pieItems) {
this.mPieItems = pieItems;
totalValue = 0;
for (PieItemBean item : mPieItems) {
totalValue += item.getItemValue();
}
invalidate();
}
private float getOffset(float radius) {
int a = (int) (radius % 360 / 90);
switch (a) {
case 0:
return radius;
case 1:
return 180 - radius;
case 2:
return radius - 180;
case 3:
return 360 - radius;
}
return radius;
}
static class PieItemBean {
private String itemType;
private float itemValue;
PieItemBean(String itemType, float itemValue) {
this.itemType = itemType;
this.itemValue = itemValue;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public float getItemValue() {
return itemValue;
}
public void setItemValue(float itemValue) {
this.itemValue = itemValue;
}
}
}
전체 인 스 턴 스 코드 는 여 기 를 클릭 하 십시오본 사이트 다운로드더 많은 안 드 로 이 드 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.,,,,,,,
본 고 에서 말 한 것 이 여러분 의 안 드 로 이 드 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.