代码改变世界

如何定制Core Plot主题

2011-03-03 16:09  乱世文章  阅读(427)  评论(0编辑  收藏  举报

CorePlot主题是一个CPTheme子类。CPTheme提供了一系列方法,你可以覆盖其中3个方法 从而实现自定义的主题:

1、 -( void )applyThemeToBackground:( CPGraph *)graph;

通过传递进来的CPGraph参数,设置背景CPGraph

2、 -( void )applyThemeToPlotArea:( CPPlotAreaFrame *)plotAreaFrame;

通过传递进来的CPPlotArea参数,设置PlotArea风格

3、 -( void )applyThemeToAxisSet:( CPAxisSet *)axisSet;

通过传递进来的CPAxisSet参数,设置坐标系风格

下面是一个CPTheme子类的例子:

一、.h文件

.h文件很简单,申明父类为CPTheme:

#import <Foundation/Foundation.h>

#import <CorePlot/CorePlot.h>

 

@interface MyCPTheme : CPXYTheme {

 

}

 

@end

二、.m文件

1、首先我们来为背景设置一个自定义颜色渐变:

-( void )applyThemeToBackground:( CPXYGraph *)graph

{

// 终点色: 20 %的灰度

CPColor *endColor = [ CPColor colorWithGenericGray : 0.2f ];

// 创建一个渐变区:起点、终点都是 0.2 的灰度

CPGradient *graphGradient = [ CPGradient gradientWithBeginningColor :endColor endingColor :endColor];

// 设置中间渐变色 1 ,位置在 30 %处,颜色为 3 0 %的灰

graphGradient = [graphGradient addColorStop :[ CPColor colorWithGenericGray : 0.3f ] atPosition : 0.3f ];

// 设置中间渐变色 2 ,位置在 50 %处,颜色为 5 0 %的灰

graphGradient = [graphGradient addColorStop :[ CPColor colorWithGenericGray : 0.5f ] atPosition : 0.5f ];

// 设置中间渐变色 3 ,位置在 60 %处,颜色为 3 0 %的灰

graphGradient = [graphGradient addColorStop :[ CPColor colorWithGenericGray : 0.3f ] atPosition : 0.6f ];

// 渐变角度:垂直 90 度(逆时针)

graphGradient. angle = 90.0f ;

// 渐变填充

graph. fill = [ CPFill fillWithGradient :graphGradient];

}

 

2、在坐标轴上画上网格线:

// Y 轴上添加平行线

-( void )applyThemeToAxisSet:( CPXYAxisSet *)axisSet {

    // 设置网格线线型

    CPLineStyle *majorGridLineStyle = [ CPLineStyle lineStyle ];

    majorGridLineStyle. lineWidth = 1.0f ;

    majorGridLineStyle. lineColor = [ CPColor lightGrayColor ];

CPXYAxis *axis=axisSet. yAxis ;

// 轴标签方向: CPSignNone -无,同 CPSignNegative CPSignPositive -反向 , y 轴的右边, CPSignNegative -正向,在 y 轴的左边

axis. tickDirection = CPSignNegative ;

// 设置平行线,默认是以大刻度线为平行线位置

    axis. majorGridLineStyle = majorGridLineStyle ;

 

// 如果 labelingPolicy 设置为 CPAxisLabelingPolicyNone majorGridLineStyle 将不起作用

    //axis.labelingPolicy = CPAxisLabelingPolicyNone ;

}

 

3、设置绘图区

下面的代码在绘图区(PlotArea)填充一个灰色渐变。注意由于绘图区(PlotArea)位于背景图(Graph)的上层(参考 Core Plot 框架的类层次图 ),因此对于绘图区所做的设置会覆盖对 Graph 所做的设置,除非你故意在 Graph 4 边留白,否则看不到背景图的设置。

-( void )applyThemeToPlotArea:( CPPlotAreaFrame *)plotAreaFrame

{

// 创建一个 20 -50 %的灰色渐变区,用于设置绘图区。

    CPGradient *gradient = [ CPGradient gradientWithBeginningColor :[ CPColor colorWithGenericGray : 0.2f ] endingColor :[ CPColor colorWithGenericGray : 0.7f ]];

    gradient. angle = 45.0f ;

// 渐变填充

plotAreaFrame. fill = [ CPFill fillWithGradient :gradient];

}

三、应用主题

很简单,将CPTheme替换成我们自己的主题,并应用到CPGraph:

#import "MyCPTheme.h"

⋯⋯

CPTheme *theme=[[ MyCPTheme alloc ] init ];

[ graph applyTheme :theme];

 

来看看效果: