二厅翔、Charts

8. Setting Colors

Since release v1.4.0, the ColorTemplate object that was responsible for setting colors in previous releases is no longer needed (deprecated). Nevertheless, it still holds all predefined color arrays (e.g. ColorTemplate.VORDIPLOM_COLORS and provides convenience methods for transforming colors from the resources (resource integers) into "real" colors.

  • 從版本v1.4.0開(kāi)始,不再需要(不建議使用)負(fù)責(zé)在先前版本中設(shè)置顏色的ColorTemplate對(duì)象蚕捉。 盡管如此碎税,它仍然保留了所有預(yù)定義的顏色數(shù)組(例如ColorTemplate.VORDIPLOM_COLORS囊骤,并提供了方便的方法,用于將顏色從資源(資源整數(shù))轉(zhuǎn)換為“真實(shí)”顏色握童。

Instead of the ColorTemplate, colors can now be specified directly via DataSet object, which allows separate styling for each DataSet.

  • 現(xiàn)在可以通過(guò)DataSet對(duì)象直接指定顏色而不是ColorTemplate姆怪,這允許為每個(gè)DataSet單獨(dú)設(shè)置樣式。

In this short example, we have our two different LineDataSet objects representing the quarterly revenues of two companies (previously mentioned in the Setting Data tutorial), for which we now want to set different colors.

  • 在這個(gè)簡(jiǎn)短的例子中澡绩,我們有兩個(gè)不同的LineDataSet對(duì)象稽揭,代表兩家公司的季度收入(之前在設(shè)置數(shù)據(jù)教程中提到過(guò)),我們現(xiàn)在想要設(shè)置不同的顏色肥卡。

What we want:

  • 我們想要什么:
  • the values of "Company 1" should be represented by four different variations of the color "red"

    • “公司1”的值應(yīng)由“紅色”的四種不同變體表示
  • the values of "Company 2" should be represented by four different variations of the color "green"

    • “公司2”的值應(yīng)由“綠色”顏色的四種不同變體表示

This is what the code looks like:

  • 這就是代碼的樣子:
LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");
  // sets colors for the dataset, resolution of the resource name to a "real" color is done internally
  setComp1.setColors(new int[] { R.color.red1, R.color.red2, R.color.red3, R.color.red4 }, Context);
  
  LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");
  setComp2.setColors(new int[] { R.color.green1, R.color.green2, R.color.green3, R.color.green4 }, Context);

Besides that, there are many other ways for setting colors for a DataSet. Here is the full documentation:

  • 除此之外溪掀,還有許多其他方法可以為DataSet設(shè)置顏色。這是完整的文檔:

setColors(int [] colors, Context c): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. You can use "new int[] { R.color.red, R.color.green, ... }" to provide colors for this method. Internally, the colors are resolved using getResources().getColor(...).

  • setColors(int [] colors步鉴,Context c):設(shè)置在此DataSet之前應(yīng)該使用的顏色揪胃。只要DataSet表示的條目數(shù)高于colors數(shù)組的大小,就會(huì)重復(fù)使用顏色氛琢。您可以使用“new int [] {R.color.red喊递,R.color.green,...}”為此方法提供顏色阳似。在內(nèi)部骚勘,使用getResources()。getColor(...)解析顏色撮奏。

setColors(int [] colors): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. Make sure that the colors are already prepared (by calling getResources().getColor(...)) before adding them to the DataSet.

  • setColors(int [] colors):設(shè)置在此DataSet之前應(yīng)使用的顏色俏讹。只要DataSet表示的條目數(shù)高于colors數(shù)組的大小,就會(huì)重復(fù)使用顏色畜吊。在將它們添加到DataSet之前藐石,請(qǐng)確保已準(zhǔn)備好顏色(通過(guò)調(diào)用getResources()。getColor(...))定拟。

setColors(ArrayList<Integer> colors): Sets the colors that should be used fore this DataSet. Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array. Make sure that the colors are already prepared (by calling getResources().getColor(...)) before adding them to the DataSet.

  • setColors(ArrayList <Integer> colors):設(shè)置在此DataSet之前應(yīng)使用的顏色于微。只要DataSet表示的條目數(shù)高于colors數(shù)組的大小逗嫡,就會(huì)重復(fù)使用顏色。在將它們添加到DataSet之前株依,請(qǐng)確保已準(zhǔn)備好顏色(通過(guò)調(diào)用getResources()驱证。getColor(...))。

setColor(int color): Sets the one and ONLY color that should be used for this DataSet. Internally, this recreates the colors array and adds the specified color.
setColor(int color):設(shè)置應(yīng)該用于此DataSet的一種顏色和唯一顏色恋腕。在內(nèi)部抹锄,這將重新創(chuàng)建顏色數(shù)組并添加指定的顏色。

ColorTemplate example:

LineDataSet set = new LineDataSet(...);
set.setColors(ColorTemplate.VORDIPLOM_COLORS);

If no colors are set for a DataSet, default colors are used.

  • 如果沒(méi)有為DataSet設(shè)置顏色荠藤,則使用默認(rèn)顏色伙单。

The ValueFormatter interface

Available since v1.6.2 - changed (improved) in v2.1.4

  • 自v1.6.2起可用 - 在v2.1.4中更改(改進(jìn))

The IValueFormatter interface can be used to create custom-made formatter classes that allow to format values within the chart (from DataSets) in a specific way before drawing them.

  • IValueFormatter接口可用于創(chuàng)建自定義格式化程序類(lèi),允許在繪制圖表之前以特定方式格式化圖表中的值(來(lái)自DataSet)哈肖。

For using the IValueFormatter, simply create a new class and let it implement the interface and return whatever you want to be displayed from the getFormattedValue(...) method.

  • 要使用IValueFormatter吻育,只需創(chuàng)建一個(gè)新類(lèi),讓它實(shí)現(xiàn)接口并從getFormattedValue(...)方法返回您想要顯示的內(nèi)容淤井。

Creating a Formatter

public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;
    
    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }
    
    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // write your logic here
        return mFormat.format(value) + " $"; // e.g. append a dollar-sign
    }
}

Then, set your formatter to the ChartData or DataSet object:

  • 然后布疼,將您的格式化程序設(shè)置為ChartData或DataSet對(duì)象:
// usage on whole data object  用于整個(gè)數(shù)據(jù)對(duì)象
lineData.setValueFormatter(new MyValueFormatter());

// usage on individual dataset object 用于單個(gè)數(shù)據(jù)集對(duì)象
lineDataSet.setValueFormatter(new MyValueFormatter());

Predefined Formatters

  • 預(yù)定義的格式化程序
  • LargeValueFormatter: Can be used for formatting large values > "1.000". It will turn values like "1.000" into "1k", "1.000.000" will be "1m" (million), "1.000.000.000" will be "1b" (billion) and values like one trillion will be e.g. "1t".

    • LargeValueFormatter:可用于格式化大值>“1.000”。 它將諸如“1.000”的值變?yōu)椤?k”币狠,“1.000.000”將變?yōu)椤?m”(百萬(wàn))游两,“1.000.000.000”將變?yōu)椤?b”(十億),并且例如一萬(wàn)億的值將是例如“1噸”漩绵。
  • PercentFormatter: Used for displaying a "%" sign after each value with 1 decimal digit. Especially useful for the PieChart. 50 -> 50.0 %

    • PercentFormatter:用于在每個(gè)值后面顯示“%”符號(hào)贱案,帶有1個(gè)十進(jìn)制數(shù)字。 對(duì)PieChart尤其有用止吐。 50 - > 50.0%
  • StackedValueFormatter: A formatter specifically designed to be used with stacked BarChart. It allows to specify whether all stack values should be drawn or just the top value.

    • StackedValueFormatter:專(zhuān)門(mén)設(shè)計(jì)用于堆疊BarChart的格式化程序宝踪。 它允許指定是應(yīng)繪制所有堆棧值還是僅繪制最高值。

The AxisValueFormatter interface

  • AxisValueFormatter接口

Introduced in release v3.0.0, this interface allows the custom styling of both XAxis and YAxisvalues before drawing.

  • 該版本在v3.0.0版本中引入祟印,允許在繪制之前自定義樣式化XAxis和YAxisvalues肴沫。

Creating a Formatter

  • 創(chuàng)建格式化程序

All that needs to be done to custom-format values on the axis is to create a class that implements the IAxisValueFormatter interface, as shown below. This formatter is used to format the values of an axis to 1 decimal digit always.

  • 所有需要對(duì)軸上的自定義格式值進(jìn)行的操作是創(chuàng)建一個(gè)實(shí)現(xiàn)IAxisValueFormatter接口的類(lèi),如下所示蕴忆。 此格式化程序用于始終將軸的值格式化為1個(gè)十進(jìn)制數(shù)颤芬。
public class MyYAxisValueFormatter implements IAxisValueFormatter {

    private DecimalFormat mFormat;

    public MyAxisValueFormatter() {

        // format values to 1 decimal digit
        mFormat = new DecimalFormat("###,###,##0.0");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mFormat.format(value) + " $";
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 1; }
}

The example below shows how to plot values from a String[] array to the axis:

  • 下面的示例顯示如何將String []數(shù)組中的值繪制到軸:
public class MyXAxisValueFormatter implements IAxisValueFormatter {

    private String[] mValues;

    public MyXAxisValueFormatter(String[] values) {
        this.mValues = values;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mValues[(int) value];
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}

Setting the Formatter

  • 設(shè)置格式化程序

After the creation of the formatter, simply set it to your axis of choice:

  • 創(chuàng)建格式化程序后,只需將其設(shè)置為您選擇的軸:
YAxis left = chart.getAxisLeft();
left.setValueFormatter(new MyYAxisValueFormatter());

String[] values = new String[] { ... };

XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyXAxisValueFormatter(values));

Instead of the default values ranging from axis minimum value to axis maximum value, the axis will now plot the data specified by the formatter.

  • 現(xiàn)在套鹅,軸將繪制格式化程序指定的數(shù)據(jù)站蝠,而不是從軸最小值到軸最大值的默認(rèn)值。

Restricting Intervals

  • 限制間隔

In case you are using a formatter based on array indices (like above), it makes sense to restrict the minimum interval of your axis to "1":

  • 如果您使用基于數(shù)組索引的格式化程序(如上所述)卓鹿,則將軸的最小間隔限制為“1”是有意義的:

This will prevent the formatter from drawing duplicate axis labels (caused by axis intervals < 1). As soon as the "zoom level" of the chart is high enough, it will stop recalculating smaller intervals.

  • 這將防止格式化程序繪制重復(fù)的軸標(biāo)簽(由軸間隔<1引起)菱魔。 只要圖表的“縮放級(jí)別”足夠高,它就會(huì)停止重新計(jì)算較小的間隔吟孙。

Predefined Formatters

  • 預(yù)定義的格式化程序
  • LargeValueFormatter: Can be used for formatting large values > "1.000". It will turn values like "1.000" into "1k", "1.000.000" will be "1m" (million), "1.000.000.000" will be "1b" (billion) and values like one trillion will be e.g. "1t".
    • LargeValueFormatter:可用于格式化大值>“1.000”澜倦。 它將諸如“1.000”的值變?yōu)椤?k”聚蝶,“1.000.000”將變?yōu)椤?m”(百萬(wàn)),“1.000.000.000”將變?yōu)椤?b”(十億)藻治,并且例如一萬(wàn)億的值將是例如“1噸”碘勉。
  • PercentFormatter: Used for displaying a "%" sign after each value with 1 decimal digit. Especially useful for the PieChart. 50 -> 50.0 %
    • PercentFormatter:用于在每個(gè)值后面顯示“%”符號(hào),帶有1個(gè)十進(jìn)制數(shù)字桩卵。 對(duì)PieChart尤其有用验靡。 50 - > 50.0%

Example Formatters

  • 示例格式化程序
  • DayAxisValueFormatter: This formatter converts the provided value to plot into a date String, altering the string depending on scale.
    • DayAxisValueFormatter:此格式化程序?qū)⑻峁┑闹缔D(zhuǎn)換為日期字符串,根據(jù)比例更改字符串雏节。
      遺留格式化程序

Legacy Formatters

  • 遺留格式化程序

Prior to release v3.0.0, there were separate formatters for XAxis and YAxis. The documentation for these formatters can be found here:

  • 在發(fā)布v3.0.0之前胜嗓,XAxis和YAxis有單獨(dú)的格式化程序。 這些格式化程序的文檔可以在這里找到:

11. General Settings & Styling

This section focuses on settings and styling of this library applicable for all Chart types.

Refreshing

  • 清爽
  • invalidate(): Calling this method on the chart will refresh (redraw) it. This is needed in order to make changes performed on the chart take effect.
    • invalidate():在圖表上調(diào)用此方法將刷新(重繪)它钩乍。 為了使圖表上執(zhí)行的更改生效辞州,需要這樣做。
  • notifyDataSetChanged(): Lets the chart know it's underlying data has changed and performs all necessary recalculations (offsets, legend, maxima, minima, ...). This is needed especially when adding data dynamically.
    • notifyDataSetChanged():讓圖表知道它的基礎(chǔ)數(shù)據(jù)已經(jīng)改變并執(zhí)行所有必要的重新計(jì)算(偏移件蚕,圖例孙技,最大值产禾,最小值排作,......)。 特別是在動(dòng)態(tài)添加數(shù)據(jù)時(shí)需要這樣做亚情。

Logging

  • 記錄
  • setLogEnabled(boolean enabled): Setting this to true will activate chart logcat output. Enabling this is bad for performance, keep disabled if not necessary.
    • setLogEnabled(boolean enabled):將此設(shè)置為true將激活圖表logcat輸出妄痪。 啟用此功能對(duì)性能有害,如果不必要楞件,請(qǐng)禁用衫生。

General Chart Styling

  • 一般圖表樣式

Here are some general styling methods you can directly use on the chart:

  • 以下是您可以在圖表上直接使用的一些通用樣式方法:
  • setBackgroundColor(int color): Sets the background color that will cover the whole chart-view. In addition, a background-color can be set via .xml in the layout file.
    • setBackgroundColor(int color):設(shè)置將覆蓋整個(gè)圖表視圖的背景顏色。 此外土浸,可以通過(guò)布局文件中的.xml設(shè)置背景顏色罪针。
  • setDescription(String desc): Set a description text that appears in the bottom right corner of the chart.
    • setDescription(String desc):設(shè)置顯示在圖表右下角的描述文本。
  • setDescriptionColor(int color): Sets the color of the description text.
    • setDescriptionColor(int color):設(shè)置描述文本的顏色黄伊。
  • setDescriptionPosition(float x, float y): Sets a custom position for the description text in pixels on the screen.
    • setDescriptionPosition(float x泪酱,float y):在屏幕上以像素為單位設(shè)置描述文本的自定義位置。
  • setDescriptionTypeface(Typeface t): Sets the Typeface used for drawing the description text.
    • setDescriptionTypeface(Typeface t):設(shè)置用于繪制描述文本的字體还最。
  • setDescriptionTextSize(float size): Sets the size of the description text in pixels, min 6f, max 16f.
    • setDescriptionTextSize(float size):設(shè)置描述文本的大小墓阀,以像素為單位,最小為6f拓轻,最大為16f斯撮。
  • setNoDataText(String text): Sets the text that should appear if the chart is empty.
    • setNoDataText(String text):設(shè)置圖表為空時(shí)應(yīng)顯示的文本。
  • setDrawGridBackground(boolean enabled): If enabled, the background rectangle behind the chart drawing-area will be drawn.
    • setDrawGridBackground(boolean enabled):如果啟用扶叉,將繪制圖表繪圖區(qū)域后面的背景矩形勿锅。
  • setGridBackgroundColor(int color): Sets the color the grid-background should be drawn with.
    • setGridBackgroundColor(int color):設(shè)置應(yīng)該使用網(wǎng)格背景繪制的顏色帕膜。
  • setDrawBorders(boolean enabled): Enables / disables drawing the chart borders (lines surrounding the chart).
    • setDrawBorders(boolean enabled):?jiǎn)⒂?禁用繪制圖表邊框(圖表周?chē)木€(xiàn)條)。
  • setBorderColor(int color): Sets the color of the chart border lines.
    • setBorderColor(int color):設(shè)置圖表邊框線(xiàn)的顏色溢十。
  • setBorderWidth(float width): Sets the width of the chart border lines in dp.
    • setBorderWidth(float width):以dp為單位設(shè)置圖表邊框線(xiàn)的寬度泳叠。
  • setMaxVisibleValueCount(int count): Sets the number of maximum visible drawn value-labels on the chart. This only takes affect when setDrawValues() is enabled.
    • setMaxVisibleValueCount(int count):設(shè)置圖表上最大可見(jiàn)繪制值標(biāo)簽的數(shù)量。 這僅在啟用setDrawValues()時(shí)生效茶宵。

12. Specific Settings & Styling

In chapter 1. Getting Started general chart settings and styling methods applicable for all chart types were mentioned. This chapter focuses on specific settings for the individual chart types.

  • 在第1章中危纫,提到了適用于所有圖表類(lèi)型的常規(guī)圖表設(shè)置和樣式方法。 本章重點(diǎn)介紹各個(gè)圖表類(lèi)型的特定設(shè)置乌庶。

Line-, Bar-, Scatter-, Candle- & BubbleChart

  • Line-种蝶,Bar-,Scatter-瞒大,Candle-和BubbleChart
  • setAutoScaleMinMaxEnabled(boolean enabled): Flag that indicates if auto scaling on the y axis is enabled. If enabled the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes. This is especially interesting for charts displaying financial data. Default: false

    • setAutoScaleMinMaxEnabled(boolean enabled):指示是否啟用y軸自動(dòng)縮放的標(biāo)志螃征。 如果啟用,則只要視口更改透敌,y軸就會(huì)自動(dòng)調(diào)整為當(dāng)前x軸范圍的最小和最大y值盯滚。 這對(duì)于顯示財(cái)務(wù)數(shù)據(jù)的圖表尤其有用。 默認(rèn)值:false
  • setKeepPositionOnRotation(boolean enabled): Sets wether the chart should keep its position (zoom / scroll) after orientation change. Default: false

    • setKeepPositionOnRotation(boolean enabled):設(shè)置方向更改后圖表應(yīng)保持其位置(縮放/滾動(dòng))酗电。 默認(rèn)值:false

BarChart

  • setDrawValueAboveBar(boolean enabled): If set to true, all values are drawn above their bars, instead of below their top.

    • setDrawValueAboveBar(boolean enabled):如果設(shè)置為true魄藕,則所有值都會(huì)在其條形圖上方繪制,而不是在其頂部之下撵术。
  • setDrawBarShadow(boolean enabled): If set to true, a grey area is drawn behind each bar that indicates the maximum value. Enabling his will reduce performance by about 40%.

    • setDrawBarShadow(boolean enabled):如果設(shè)置為true背率,則在每個(gè)條形后面繪制一個(gè)灰色區(qū)域,指示最大值嫩与。 啟用他的功能會(huì)使性能降低約40%寝姿。
  • setDrawValuesForWholeStack(boolean enabled): If set to true, all values of stacked bars are drawn individually, and not just their sum on top of all.

    • setDrawValuesForWholeStack(boolean enabled):如果設(shè)置為true,則堆疊條形的所有值都是單獨(dú)繪制的划滋,而不僅僅是它們之和的總和饵筑。
  • setDrawHighlightArrow(boolean enabled): Set this to true to draw the highlightning arrow above each bar when highlighted.

    • setDrawHighlightArrow(boolean enabled):將此項(xiàng)設(shè)置為true可在突出顯示時(shí)在每個(gè)條形圖上方繪制突出顯示箭頭。

PieChart

  • setDrawSliceText(boolean enabled): Set this to true to draw the x-value text into the pie slices.

    • setDrawSliceText(boolean enabled):將此值設(shè)置為true可將x值文本繪制到餅圖切片中处坪。
  • setUsePercentValues(boolean enabled): If this is enabled, values inside the chart are drawn in percent and not with their original value. Values provided for the ValueFormatterto format are then provided in percent.

    • setUsePercentValues(boolean enabled):如果啟用此選項(xiàng)根资,則圖表中的值將以百分比形式繪制,而不是以其原始值繪制稻薇。 然后以百分比形式提供為ValueFormatterto格式提供的值嫂冻。
  • setCenterText(SpannableString text): Sets the text that is drawn in the center of the PieChart. Longer text will be automatically "wrapped" to avoid clipping into the pie-slices.

    • setCenterText(SpannableString text):設(shè)置在PieChart中心繪制的文本。 較長(zhǎng)的文本將自動(dòng)“包裝”以避免剪切到餅圖切片中塞椎。
  • setCenterTextRadiusPercent(float percent): Sets the rectangular radius of the bounding box for the center text, as a percentage of the pie hole default 1.f (100%).

    • setCenterTextRadiusPercent(float percent):設(shè)置中心文本邊界框的矩形半徑桨仿,以餅圖孔默認(rèn)值1.f(100%)的百分比表示。
  • setHoleRadius(float percent): Sets the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart), default 50%

    • setHoleRadius(float percent):以最大半徑的百分比(max =整個(gè)圖表的半徑)設(shè)置餅圖中心的孔半徑案狠,默認(rèn)為50%
  • setTransparentCircleRadius(float percent): Sets the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart), default 55% -> means 5% larger than the center-hole by default

    • setTransparentCircleRadius(float percent):設(shè)置在餅圖中孔旁邊繪制的透明圓的半徑服傍,以最大半徑的百分比表示(max =整個(gè)圖表的半徑)钱雷,默認(rèn)為55% - >表示大于5% 默認(rèn)為中心孔
  • setTransparentCircleColor(int color): Sets the color of the transparent circle.

    • setTransparentCircleColor(int color):設(shè)置透明圓的顏色。
  • setTransparentCircleAlpha(int alpha): Sets the amount of transparency (0-255) the transparent circle should have.

    • setTransparentCircleAlpha(int alpha):設(shè)置透明圓圈應(yīng)具有的透明度(0-255)吹零。
  • setMaxAngle(float maxangle): Sets the max angle that is used for calculating the pie-circle. 360f means it's a full PieChart, 180f results in a half-pie-chart. Default: 360f

    • setMaxAngle(float maxangle):設(shè)置用于計(jì)算餅圈的最大角度罩抗。 360f意味著它是一個(gè)完整的PieChart,180f會(huì)產(chǎn)生一個(gè)半餅圖灿椅。 默認(rèn)值:360f

RadarChart

  • RadarChart
  • setSkipWebLineCount(int count): Allows to skip web lines coming from the center of the chart. Especially useful if there are a lot of lines.
    • setSkipWebLineCount(int count):允許跳過(guò)來(lái)自圖表中心的Web行套蒂。 如果有很多行,特別有用茫蛹。

13. Legend

By default, all chart types support legends and will automatically generate and draw a legend after setting data for the chart. The Legend usually consists of multiple entries each represented by a label an a form/shape.

  • 默認(rèn)情況下操刀,所有圖表類(lèi)型都支持圖例,并在設(shè)置圖表數(shù)據(jù)后自動(dòng)生成并繪制圖例婴洼。 圖例通常由多個(gè)條目組成骨坑,每個(gè)條目由標(biāo)簽和形狀/形狀表示。

The number of entries the automatically generated legend contains depends on the number of different colors (across all DataSet objects) as well as on the DataSet labels. The labels of the Legend depend on the labels set for the used DataSet objects in the chart. If no labels for the DataSet objects have been specified, the chart will automatically generate them. If multiple colors are used for one DataSet, those colors are grouped and only described by (belong to) one label.

  • 自動(dòng)生成的圖例包含的條目數(shù)取決于不同顏色的數(shù)量(跨所有DataSet對(duì)象)以及DataSet標(biāo)簽柬采。 圖例的標(biāo)簽取決于為圖表中使用的DataSet對(duì)象設(shè)置的標(biāo)簽欢唾。 如果未指定DataSet對(duì)象的標(biāo)簽,則圖表將自動(dòng)生成它們粉捻。 如果一個(gè)DataSet使用多種顏色礁遣,則這些顏色被分組,并且僅由(屬于)一個(gè)標(biāo)簽描述杀迹。

For customizing the Legend, use you can retreive the Legend object from the chart using the getLegend() method:

  • 要自定義圖例亡脸,可以使用getLegend()方法從圖表中檢索Legend對(duì)象:
Legend legend = chart.getLegend();
Control if the legend should be drawn
  • 控制是否應(yīng)繪制圖例

setEnabled(boolean enabled): Sets the Legend enabled or disabled. If disabled, the Legend will not be drawn.

  • setEnabled(boolean enabled):設(shè)置啟用或禁用圖例押搪。 如果禁用树酪,則不會(huì)繪制圖例。
Styling / modifying the legend
  • setEnabled(boolean enabled):設(shè)置啟用或禁用圖例大州。 如果禁用续语,則不會(huì)繪制圖例。

setTextColor(int color): Sets the color of the legend labels.

  • setTextColor(int color):設(shè)置圖例標(biāo)簽的顏色厦画。

setTextSize(float size): Sets the text-size of the legend labels in dp.

  • setTextSize(float size):設(shè)置dp中圖例標(biāo)簽的文本大小疮茄。

setTypeface(Typeface tf): Sets a custom Typeface for the legend labels.

  • setTypeface(Typeface tf):為圖例標(biāo)簽設(shè)置自定義字體。
Wrapping / clipping avoidance
  • 避免纏繞/剪裁

setWordWrapEnabled(boolean enabled): If enabled, the content of the legend will not clip outside the charts bounds, but instead create a new line. Please note that this reduces performance and is only available for legends below the chart.

  • setWordWrapEnabled(boolean enabled):如果啟用根暑,圖例的內(nèi)容將不會(huì)在圖表邊界之外剪切力试,而是創(chuàng)建一個(gè)新行。 請(qǐng)注意,這會(huì)降低性能,僅適用于圖表下方的圖例到忽。

setMaxSizePercent(float maxSize): Sets the maximum relative size out of the whole chart view in percent. Default: 0.95f (95%)

  • setMaxSizePercent(float maxSize):以百分比形式設(shè)置整個(gè)圖表視圖的最大相對(duì)大小累颂。 默認(rèn)值:0.95f(95%)
Customizing the legend
  • 自定義圖例

setPosition(LegendPosition pos): Sets the LegendPosition which defines where the Legend should appear. Choose between RIGHT_OF_CHART, RIGHT_OF_CHART_CENTER, RIGHT_OF_CHART_INSIDE, BELOW_CHART_LEFT, BELOW_CHART_RIGHT, BELOW_CHART_CENTER or PIECHART_CENTER (PieChart only), ... and more.

  • setPosition(LegendPosition pos):設(shè)置LegendPosition瞪醋,用于定義Legend應(yīng)出現(xiàn)的位置迅腔。 選擇RIGHT_OF_CHART牍帚,RIGHT_OF_CHART_CENTER银伟,RIGHT_OF_CHART_INSIDE伍伤,BELOW_CHART_LEFT并徘,BELOW_CHART_RIGHT,BELOW_CHART_CENTER或PIECHART_CENTER(僅限PieChart)扰魂,......等等麦乞。

setForm(LegendForm shape): Sets the LegendForm that should be used. This is the shape that is drawn next to the legend-labels with the color of the DataSet the legend-entry represents. Choose between SQUARE, CIRCLE or LINE.

  • setForm(LegendForm shape):設(shè)置應(yīng)該使用的LegendForm。 這是在圖例標(biāo)簽旁邊繪制的形狀劝评,其中包含圖例條目所代表的DataSet的顏色路幸。 在SQUARE,CIRCLE或LINE之間進(jìn)行選擇付翁。

setFormSize(float size): Sets the size of the legend-forms in dp.

  • setFormSize(float size):設(shè)置dp中圖例形式的大小简肴。

setXEntrySpace(float space): Sets the space between the legend-entries on the horizontal axis.

  • setXEntrySpace(float space):設(shè)置水平軸上圖例條目之間的間距。

setYEntrySpace(float space): Sets the space between the legend-entries on the vertical axis.

  • setYEntrySpace(float space):設(shè)置垂直軸上圖例條目之間的間距百侧。

setFormToTextSpace(float space): Sets the space between the legend-label and the corresponding legend-form.

  • setFormToTextSpace(float space):設(shè)置圖例標(biāo)簽和相應(yīng)圖例表單之間的空格砰识。

setWordWrapEnabled(boolean enabled): Should the legend word wrap? / this is currently supported only for BelowChartLeft, BelowChartRight, BelowChartCenter. / you may want to set maxSizePercent when word wrapping, to set the point where the text wraps.

  • setWordWrapEnabled(boolean enabled):圖例文字是否應(yīng)該換行? /目前僅支持BelowChartLeft佣渴,BelowChartRight辫狼,BelowChartCenter。 /你可能想在自動(dòng)換行時(shí)設(shè)置maxSizePercent辛润,以設(shè)置文本換行的點(diǎn)膨处。
Setting custom labels & colors
  • 設(shè)置自定義標(biāo)簽和顏色

setCustom(int[] colors, String[] labels): Sets a custom legend's labels and colors arrays. The colors count should match the labels count. Each color is for the form drawn at the same index. A null label will start a group. A (-2) color will avoid drawing a form This will disable the feature that automatically calculates the legend labels and colors from the datasets. Call resetCustom() to re-enable automatic calculation (and then notifyDataSetChanged() is needed to auto-calculate the legend again)

  • setCustom(int [] colors,String [] labels):設(shè)置自定義圖例的標(biāo)簽和顏色數(shù)組砂竖。 顏色計(jì)數(shù)應(yīng)與標(biāo)簽數(shù)量匹配真椿。 每種顏色用于在相同索引處繪制的表單。 空標(biāo)簽將啟動(dòng)一個(gè)組乎澄。 (-2)顏色將避免繪制表單這將禁用自動(dòng)計(jì)算數(shù)據(jù)集中的圖例標(biāo)簽和顏色的功能突硝。 調(diào)用resetCustom()重新啟用自動(dòng)計(jì)算(然后需要notifyDataSetChanged()再次自動(dòng)計(jì)算圖例)

resetCustom(): Calling this will disable the custom legend labels (set by setCustom(...)). Instead, the labels will again be calculated automatically (after notifyDataSetChanged() is called).

  • resetCustom():調(diào)用此方法將禁用自定義圖例標(biāo)簽(由setCustom(...)設(shè)置)。 相反置济,將再次自動(dòng)計(jì)算標(biāo)簽(在調(diào)用notifyDataSetChanged()之后)解恰。

setExtra(int[] colors, String[] labels): Sets colors and labels that will be appended to the end of the auto calculated colors and labels arrays after calculating the legend. (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect)

  • setExtra(int [] colors,String [] labels):設(shè)置在計(jì)算圖例后將附加到自動(dòng)計(jì)算顏色和標(biāo)簽數(shù)組末尾的顏色和標(biāo)簽浙于。 (如果已經(jīng)計(jì)算了圖例护盈,則需要調(diào)用notifyDataSetChanged()以使更改生效)

Example

Legend l = chart.getLegend();
    l.setFormSize(10f); // set the size of the legend forms/shapes
    l.setForm(LegendForm.CIRCLE); // set what type of form/shape should be used
    l.setPosition(LegendPosition.BELOW_CHART_LEFT);
    l.setTypeface(...);
    l.setTextSize(12f);
    l.setTextColor(Color.BLACK);
    l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
    l.setYEntrySpace(5f); // set the space between the legend entries on the y-axis

    // set custom labels and colors
    l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "Set1", "Set2", "Set3", "Set4", "Set5" });

    // and many more...

14. Dynamic & Realtime Data

Getting started

MPAndroidChart does not offically support realtime data, however, for adding new data to the chart or removing data dynamically, there are various methods that allow to either add or remove Entry objects to an existing DataSet or DataSet objects to/from an existing ChartDataobject.

  • MPAndroidChart不會(huì)正式支持實(shí)時(shí)數(shù)據(jù),但是羞酗,為了向圖表添加新數(shù)據(jù)或動(dòng)態(tài)刪除數(shù)據(jù)腐宋,有多種方法可以向現(xiàn)有的ChartData對(duì)象添加或刪除現(xiàn)有DataSet或DataSet對(duì)象的Entry對(duì)象。

Possibilities of adding / removing data dynamically

Class DataSet (and all subclasses):

  • addEntry(Entry e): Adds the given Entry object to the DataSet.
    • addEntry(Entry e):將給定的Entry對(duì)象添加到DataSet。
      ChartData類(lèi)(和所有子類(lèi)):
Class ChartData (and all subclasses):
  • 類(lèi)DataSet(和所有子類(lèi)):
  • addEntry(Entry e, int dataSetIndex): Adds the given Entry to the DataSet at the specified dataset index.
    • addEntry(Entry e脏款,int dataSetIndex):將給定的Entry添加到指定數(shù)據(jù)集索引處的DataSet围苫。
  • addDataSet(DataSet d): Adds the given DataSet object to the ChartData object.
    • addDataSet(DataSet d):將給定的DataSet對(duì)象添加到ChartData對(duì)象。

In addition to that, there are also methods for removing data dynamically:

  • 除此之外撤师,還有一些動(dòng)態(tài)刪除數(shù)據(jù)的方法:
Class DataSet (and all subclasses):
  • public boolean removeFirst(): Removes the first Entry (at index 0) of this DataSet from the entries array. Returns true if successful, false if not.

    • public boolean removeFirst():從entries數(shù)組中刪除此DataSet的第一個(gè)Entry(在索引0處)剂府。 如果成功則返回true,否則返回false剃盾。
  • public boolean removeLast(): Removes the last Entry (at index size-1) of this DataSet from the entries array. Returns true if successful, false if not.

    • public boolean removeLast():從entries數(shù)組中刪除此DataSet的最后一個(gè)Entry(索引大小為-1)腺占。 如果成功則返回true,否則返回false痒谴。
  • public boolean removeEntry(Entry e): Removes the given Entry object from the DataSet. Returns true if successful.

    • public boolean removeEntry(Entry e):從DataSet中刪除給定的Entry對(duì)象衰伯。 如果成功則返回true。
  • public boolean removeEntry(int xIndex): Removes the Entry at the given x-index from the DataSet. Returns true if successful.

    • public boolean removeEntry(int xIndex):從DataSet中刪除給定x-index處的Entry积蔚。 如果成功則返回true意鲸。
Class ChartData (and all subclasses):
  • ChartData類(lèi)(和所有子類(lèi)):
  • public boolean removeEntry(Entry e, int dataSetIndex): Removes the given Entryobject from the DataSet with the given dataset index. Returns true if successful.

    • public boolean removeEntry(Entry e,int dataSetIndex):使用給定的數(shù)據(jù)集索引從DataSet中刪除給定的Entry對(duì)象尽爆。 如果成功則返回true怎顾。
  • public boolean removeEntry(int xIndex, int dataSetIndex): Removes the Entry at the given x-index from the DataSet with the given dataset index. Returns true if successful.

    • public boolean removeEntry(int xIndex,int dataSetIndex):使用給定的數(shù)據(jù)集索引從DataSet中移除給定x-index處的Entry漱贱。 如果成功則返回true槐雾。
  • public boolean removeDataSet(DataSet d): Removes the given DataSet object from the ChartData object. Returns true if successful.

    • public boolean removeDataSet(DataSet d):從ChartData對(duì)象中刪除給定的DataSet對(duì)象。 如果成功則返回true幅狮。
  • public boolean removeDataSet(int index): Removes the DataSet at the given index from the ChartData object. Returns true if successful.

    • public boolean removeDataSet(int index):從ChartData對(duì)象中刪除給定索引處的DataSet募强。 如果成功則返回true。
Keep in mind

After adding or removing data dynamically, notifyDataSetChanged() must be called on the chart before refreshing it (by calling invalidate()).

  • 在動(dòng)態(tài)添加或刪除數(shù)據(jù)之后崇摄,必須在刷新之前在圖表上調(diào)用notifyDataSetChanged()(通過(guò)調(diào)用invalidate())擎值。
 // EXAMPLE 1
 // add entries to the "data" object
 exampleData.addEntry(...);
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

 // EXAMPLE 2
 // add entries to "dataSet" object
 dataSet.addEntry(...);
 exampleData.notifyDataChanged(); // let the data know a dataSet changed
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

Note: Methods like moveViewTo(...) will automatically call invalidate().

  • 注意:moveViewTo(...)之類(lèi)的方法會(huì)自動(dòng)調(diào)用invalidate()。

15. Modifying the Viewport

This library has various methods for modifying the viewport (what is visible on the chart, aim of the view). Please note that these methods are only available for the LineChart, BarChart, ScatterChart and CandleStickChart.

  • 此庫(kù)具有各種用于修改視口的方法(圖表上可見(jiàn)的內(nèi)容配猫,視圖的目標(biāo))幅恋。 請(qǐng)注意,這些方法僅適用于LineChart泵肄,BarChart,ScatterChart和CandleStickChart淑翼。

The methods mentioned below are provided by the Chart class. Another way to modify the viewport is to directly access it (without the in-between safety provided by the chart) via the ViewPortHandler. This is only recommended for advanced users who are familiar with the API.

  • 下面提到的方法由Chart類(lèi)提供腐巢。 修改視口的另一種方法是通過(guò)ViewPortHandler直接訪(fǎng)問(wèn)它(沒(méi)有圖表提供的中間安全性)。 這僅適用于熟悉API的高級(jí)用戶(hù)玄括。

Please note that all methods modifying the viewport need to be called on the Chart after setting data.

  • 請(qǐng)注意冯丙,在設(shè)置數(shù)據(jù)后,需要在圖表上調(diào)用修改視口的所有方法。

Restraining what's visible

setVisibleXRangeMaximum(float maxXRange): Sets the size of the area (range on the x-axis) that should be maximum visible at once. If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.

  • setVisibleXRangeMaximum(float maxXRange):設(shè)置應(yīng)該一次最大可見(jiàn)的區(qū)域大形赶А(x軸上的范圍)泞莉。如果這是例如設(shè)置為10,可以一次查看x軸上不超過(guò)10個(gè)值而無(wú)需滾動(dòng)船殉。

setVisibleXRangeMinimum(float minXRange): Sets the size of the area (range on the x-axis) that should be minimum visible at once. If this is e.g. set to 10, it is not possible to zoom in further than 10 values on the x-axis.

  • setVisibleXRangeMinimum(float minXRange):設(shè)置應(yīng)該一次最小可見(jiàn)的區(qū)域大婿瓿谩(x軸上的范圍)。如果這是例如如果設(shè)置為10利虫,則無(wú)法在x軸上放大10個(gè)以上的值挨厚。

setVisibleYRangeMaximum(float maxYRange, AxisDependency axis): Sets the size of the area (range on the y-axis) that should be maximum visible at once. You also need to provide the axis this constraint should apply to.

  • setVisibleYRangeMaximum(float maxYRange,AxisDependency axis):設(shè)置應(yīng)該一次最大可見(jiàn)的區(qū)域大锌繁埂(y軸上的范圍)疫剃。您還需要提供此約束應(yīng)適用的軸。

setViewPortOffsets(float left, float top, float right, float bottom): Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this. USE THIS ONLY WHEN YOU KNOW WHAT YOU ARE DOING.

  • setViewPortOffsets(向左浮動(dòng)硼讽,向上浮動(dòng)巢价,向右浮動(dòng),浮動(dòng)底部):設(shè)置當(dāng)前ViewPort的自定義偏移(實(shí)際圖表窗口兩側(cè)的偏移)固阁。設(shè)置此項(xiàng)將阻止圖表自動(dòng)計(jì)算其偏移量蹄溉。使用resetViewPortOffsets()來(lái)撤消此操作。只有在你知道你做什么的時(shí)候才使用它您炉。

resetViewPortOffsets(): Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.

  • resetViewPortOffsets():重置通過(guò)setViewPortOffsets(...)方法設(shè)置的所有自定義偏移柒爵。允許圖表再次自動(dòng)計(jì)算所有偏移量。

setExtraOffsets(float left, float top, float right, float bottom): Sets extra offsets (around the chart view) to be appended to the auto-calculated offsets. This does not change the auto-calculated offsets, but adds extra space to them.

  • setExtraOffsets(向左浮動(dòng)赚爵,浮動(dòng)頂部棉胀,向右浮動(dòng),浮動(dòng)底部):設(shè)置要附加到自動(dòng)計(jì)算的偏移的額外偏移(在圖表視圖周?chē)┘较ァ_@不會(huì)更改自動(dòng)計(jì)算的偏移量唁奢,但會(huì)為它們?cè)黾宇~外的空間。
Moving the view (where it is aimed)

fitScreen(): Resets all zooming and dragging and makes the chart fit exactly it's bounds (fully zoom out).

  • fitScreen():重置所有縮放和拖動(dòng)窝剖,使圖表完全適合它的邊界(完全縮新榈А)。

moveViewToX(float xValue): Moves the left side (edge) of the current viewport to the specified x-value.

  • moveViewToX(float xValue):將當(dāng)前視口的左側(cè)(邊)移動(dòng)到指定的x值赐纱。

moveViewToY(float yValue, AxisDependency axis): Centers the viewport to the specified y-value on the provided y-axis (left or right).

  • moveViewToY(float yValue脊奋,AxisDependency axis):將視口居中于提供的y軸(左側(cè)或右側(cè))上的指定y值。

moveViewTo(float xValue, float yValue, AxisDependency axis): This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the provided y-axis (makes sense in combination with setVisibleXRange(...) and setVisibleYRange(...).

  • moveViewTo(float xValue疙描,float yValue诚隙,AxisDependency axis):這會(huì)將當(dāng)前視口的左側(cè)移動(dòng)到x軸上的指定x值,并將視口居中于提供的y軸上的指定y值 (與setVisibleXRange(...)和setVisibleYRange(...)結(jié)合使用是有意義的起胰。

centerViewTo(float xValue, float yValue, AxisDependency axis): This will move the center of the current viewport to the specified x-value and y-value (makes sense in combination with setVisibleXRange(...) and setVisibleYRange(...).

  • centerViewTo(float xValue久又,float yValue,AxisDependency axis):這會(huì)將當(dāng)前視口的中心移動(dòng)到指定的x值和y值(與setVisibleXRange(...)和setVisibleYRange(...)結(jié)合使用)。

Moving the view with animations

(since release v2.2.3)

  • moveViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the provided y-axis in an animated way.
    • moveViewToAnimated(float xValue地消,float yValue炉峰,AxisDependency axis,long duration):這會(huì)將當(dāng)前視口的左側(cè)移動(dòng)到x軸上的指定x值脉执,并將視口居中放置在提供的指定y值上 y軸以動(dòng)畫(huà)方式疼阔。
  • centerViewToAnimated(float xValue, float yValue, AxisDependency axis, long duration): This will move the center of the current viewport to the specified x-value and y-value (according to axis) in an animated way.
    • centerViewToAnimated(float xValue,float yValue适瓦,AxisDependency axis竿开,long duration):這將以動(dòng)畫(huà)方式將當(dāng)前視口的中心移動(dòng)到指定的x值和y值(根據(jù)軸)。

Note: All moveViewTo(...) methods will automatically invalidate() (refresh) the chart. There is no need for further calling invalidate().

  • 注意:所有moveViewTo(...)方法都將自動(dòng)使圖表無(wú)效()(刷新)玻熙。 無(wú)需進(jìn)一步調(diào)用invalidate()否彩。

Zooming (programmatically)

  • zoomIn(): Zooms in by 1.4f, into the charts center.

    • zoomIn():放大1.4f,進(jìn)入圖表中心嗦随。
  • zoomOut(): Zooms out by 0.7f, from the charts center.

    • zoomOut():從圖表中心縮小0.7f列荔。
  • zoom(float scaleX, float scaleY, float x, float y): Zooms in or out by the given scale factor. x and y are the coordinates (in pixels) of the zoom center. Remember that a scale of 1f = no zoom.

    • zoom(float scaleX,float scaleY枚尼,float x贴浙,float y):按給定的比例因子放大或縮小。 x和y是變焦中心的坐標(biāo)(以像素為單位)署恍。 請(qǐng)記住崎溃,1f的比例=無(wú)縮放。
  • zoom(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis): Zooms in or out by the given scale factor. xValue and yValue are the actual data values (not pixels) of the zoom center. Remember that a scale of 1f = no zoom.

    • zoom(float scaleX盯质,float scaleY袁串,float xValue,float yValue呼巷,AxisDependency axis):按給定的比例因子放大或縮小囱修。 xValue和yValue是縮放中心的實(shí)際數(shù)據(jù)值(不是像素)。 請(qǐng)記住王悍,1f的比例=無(wú)縮放破镰。

Zooming with animations

(since release v2.2.3)

  • zoomAndCenterAnimated(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis, long duration): Zooms by the specified scale factor and centers the viewport to the specified values on the specified axis in an animated way.
  • zoomAndCenterAnimated(float scaleX,float scaleY压储,float xValue鲜漩,float yValue,AxisDependency axis渠脉,long duration):縮放指定的縮放系數(shù)宇整,并以動(dòng)畫(huà)方式將視口居中指定軸上的指定值。
Full example
chart.setData(...); // first set data

// now modify viewport
chart.setVisibleXRangeMaximum(20); // allow 20 values to be displayed at once on the x-axis, not more
chart.moveViewToX(10); // set the left edge of the chart to x-index 10
// moveViewToX(...) also calls invalidate()

16. Animations

Note: ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.

On lower Android versions, animations will not be executed (but will not crash).

  • 在較低的Android版本中芋膘,動(dòng)畫(huà)將不會(huì)執(zhí)行(但不會(huì)崩潰)。

All chart types support animations that can be used to create / build up the chart in an awesome looking way. Three different kinds of animation methods exist that animate either both, or x- and y-axis separately:

  • 所有圖表類(lèi)型都支持動(dòng)畫(huà),可用于以令人敬畏的方式創(chuàng)建/構(gòu)建圖表为朋。 存在三種不同的動(dòng)畫(huà)方法臂拓,分別為兩者或x軸和y軸設(shè)置動(dòng)畫(huà):

animateX(int durationMillis): Animates the charts values on the horizontal axis, meaning that the chart will build up within the specified time from left to right.

  • animateX(int durationMillis):在水平軸上設(shè)置圖表值的動(dòng)畫(huà),這意味著圖表將在從左到右的指定時(shí)間內(nèi)建立习寸。

animateY(int durationMillis): Animates the charts values on the vertical axis, meaning that the chart will build up within the specified time from bottom to top.

  • animateY(int durationMillis):在垂直軸上設(shè)置圖表值的動(dòng)畫(huà)胶惰,這意味著圖表將在從下到上的指定時(shí)間內(nèi)構(gòu)建。

animateXY(int xDuration, int yDuration): Animates both horizontal and vertical axis, resulting in a left/right bottom/top build-up.

  • animateXY(int xDuration霞溪,int yDuration):為水平和垂直軸設(shè)置動(dòng)畫(huà)孵滞,從而產(chǎn)生左/右底/頂部構(gòu)建。
mChart.animateX(3000); // animate horizontal 3000 milliseconds
// or:
mChart.animateY(3000); // animate vertical 3000 milliseconds
// or:
mChart.animateXY(3000, 3000); // animate horizontal and vertical 3000 milliseconds

If animate(...) (of any kind) is called, no further calling of invalidate() is necessary to refresh the chart.

  • 如果調(diào)用animate(...)(任何類(lèi)型)鸯匹,則不需要再次調(diào)用invalidate()來(lái)刷新圖表坊饶。

Animation easing

  • 動(dòng)畫(huà)緩和

This library allows you to apply nice easing functions to your animations. You can choose between the following static predefined Easing.EasingOption:

  • 該庫(kù)允許您將漂亮的緩動(dòng)函數(shù)應(yīng)用于動(dòng)畫(huà)。 您可以在以下靜態(tài)預(yù)定義Easing.EasingOption之間進(jìn)行選擇:
  public enum EasingOption {
      Linear,
      EaseInQuad,
      EaseOutQuad,
      EaseInOutQuad,
      EaseInCubic,
      EaseOutCubic,
      EaseInOutCubic,
      EaseInQuart,
      EaseOutQuart,
      EaseInOutQuart,
      EaseInSine,
      EaseOutSine,
      EaseInOutSine,
      EaseInExpo,
      EaseOutExpo,
      EaseInOutExpo,
      EaseInCirc,
      EaseOutCirc,
      EaseInOutCirc,
      EaseInElastic,
      EaseOutElastic,
      EaseInOutElastic,
      EaseInBack,
      EaseOutBack,
      EaseInOutBack,
      EaseInBounce,
      EaseOutBounce,
      EaseInOutBounce,
  }

Basically, there are two ways of easing your animation:

  • 基本上殴蓬,有兩種方法可以簡(jiǎn)化動(dòng)畫(huà):
  1. Predefined easing options: (this code will run on any Android version)
  • 預(yù)定義的緩動(dòng)選項(xiàng):(此代碼可在任何Android版本上運(yùn)行)
public void animateY(int durationmillis, Easing.EasingOption option); 

Call any animation method with a predefined easing option:

  • 使用預(yù)定義的緩動(dòng)選項(xiàng)調(diào)用任何動(dòng)畫(huà)方法:
// animate both axes with easing 用緩動(dòng)動(dòng)畫(huà)兩個(gè)軸
mChart.animateY(3000, Easing.EasingOption.EaseOutBack); 

Always use Easing.EasingOption for predefined animation easing when you want your code to run below Android 3.0 (API level 11).

  • 當(dāng)您希望代碼在Android 3.0(API級(jí)別11)以下運(yùn)行時(shí)匿级,請(qǐng)始終使用Easing.EasingOption進(jìn)行預(yù)定義的動(dòng)畫(huà)緩動(dòng)。
  1. Custom easing functions: (custom easing functions will crash below Android 3.0)
  • 自定義緩動(dòng)功能:(自定義緩動(dòng)功能將在Android 3.0下崩潰)
public void animateY(int durationmillis, EasingFunction function); 

Create your own easing functions by creating your own easing-function class and implementing the EasingFunction interface:

  • 通過(guò)創(chuàng)建自己的緩動(dòng)函數(shù)類(lèi)并實(shí)現(xiàn)EasingFunction接口來(lái)創(chuàng)建自己的緩動(dòng)函數(shù):
/**
 * Interface for creating custom made easing functions. 
  * 用于創(chuàng)建自定義緩動(dòng)函數(shù)的界面染厅。
 */
 public interface EasingFunction {
    /**
     * Called everytime the animation is updated.
      * 每次動(dòng)畫(huà)更新時(shí)調(diào)用痘绎。
     * @param input - the time passed since the animation started (value between 0 and 1)
      * 動(dòng)畫(huà)開(kāi)始后經(jīng)過(guò)的時(shí)間(0到1之間的值)
     */
     public float getInterpolation(float input);
 }

Then call it this way (be aware, this will not run below Android 3.0 and crash):

  • 然后以這種方式調(diào)用它(請(qǐng)注意,這不會(huì)在Android 3.0下運(yùn)行并崩潰):
// animate both axes with easing  用緩動(dòng)動(dòng)畫(huà)兩個(gè)軸
mChart.animateY(3000, new MyEasingFunction()); 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末肖粮,一起剝皮案震驚了整個(gè)濱河市孤页,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌涩馆,老刑警劉巖行施,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異凌净,居然都是意外死亡悲龟,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)冰寻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)须教,“玉大人,你說(shuō)我怎么就攤上這事斩芭∏嵯伲” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵划乖,是天一觀的道長(zhǎng)贬养。 經(jīng)常有香客問(wèn)我,道長(zhǎng)琴庵,這世上最難降的妖魔是什么误算? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任仰美,我火速辦了婚禮,結(jié)果婚禮上儿礼,老公的妹妹穿的比我還像新娘咖杂。我一直安慰自己,他們只是感情好蚊夫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布诉字。 她就那樣靜靜地躺著,像睡著了一般知纷。 火紅的嫁衣襯著肌膚如雪壤圃。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天琅轧,我揣著相機(jī)與錄音伍绳,去河邊找鬼。 笑死鹰晨,一個(gè)胖子當(dāng)著我的面吹牛墨叛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播模蜡,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼漠趁,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了忍疾?” 一聲冷哼從身側(cè)響起闯传,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎卤妒,沒(méi)想到半個(gè)月后甥绿,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡则披,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年共缕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片士复。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡图谷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出阱洪,到底是詐尸還是另有隱情便贵,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布冗荸,位于F島的核電站承璃,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚌本。R本人自食惡果不足惜盔粹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一隘梨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧玻佩,春花似錦出嘹、人聲如沸席楚。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)烦秩。三九已至垮斯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間只祠,已是汗流浹背兜蠕。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留抛寝,地道東北人熊杨。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像盗舰,于是被迫代替她去往敵國(guó)和親晶府。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評(píng)論 0 10
  • 房間亂糟糟:地板已經(jīng)三個(gè)星期沒(méi)有清理了钻趋,前天舍友來(lái)我這涮鍋川陆,各種液體落在地上,現(xiàn)在已經(jīng)變成一塊塊黑灰色印記蛮位;黑色的...
    知_是閱讀 440評(píng)論 0 1
  • 《自私的基因》是英國(guó)生物學(xué)家理查德·道金斯所寫(xiě)较沪,書(shū)中認(rèn)為達(dá)爾文的“適者生存”其實(shí)是穩(wěn)定者生存;宇宙是為一種穩(wěn)定的物...
    江蘇劉志祥閱讀 167評(píng)論 0 1
  • 我想我應(yīng)該是一只鬼 無(wú)人問(wèn)津 孤獨(dú)無(wú)依 鬼像一個(gè)遺棄在路邊的破易拉罐 只有可憐的孤苦老人 伸出滿(mǎn)是皺紋的手 拿去換...
    溫瑯閱讀 512評(píng)論 2 6
  • 其實(shí) 不管你怎么做 不管你怎么改變 總會(huì)有人喜歡你 總會(huì)有人不喜歡你 有人喜歡我 挺好的 有人不喜歡我 也挺好的 ...
    小伊Eva閱讀 123評(píng)論 0 0