读书人

CorePlot:用图片定做坐标轴标签

发布时间: 2012-08-24 10:00:21 作者: rapoo

CorePlot:用图片定制坐标轴标签

原文:http://stackoverflow.com/questions/6748996/how-to-set-custom-tick-marks-in-core-plot-to-icons

Axis label 可以使用任何 CPTLayer(CALayer 子类)作为标签。用UIImage 作为 CPTLayer 的背景层即可定制轴标签。有许多Core Plot 的使用定制轴标签的例子,虽然他们用的是文本标签。

有两种方法定制图形类的轴标签:

1、 graph的labeling policy设置为CPTAxisLabelingPolicyNone。创建NSSet,放入所有 AxisLabel,然后将坐标轴的 axisLabels 属性设置为 NSSet。如果用这种方法,你需要提供major/minor tick的location。

2、labeling policy 设置为其他策略,以产生 major/minor tick。然后实现axis:shouldUpdateAxisLabelsAtLocations:委托方法。在方法中,在指定的location创建新的label 然后返回 No 以忽略默认的标签。

Jul 19 '11 at 22:46

Eric Skroch

根据 Eric 的说法,我编写了一些代码,以供参考:

if (yAxisIcons) {

int custonLabelsCount = [self.yAxisIcons count];

NSMutableArray *customLabels =[NSMutableArray arrayWithCapacity:custonLabelsCount];

for (NSUInteger i = 0; i <custonLabelsCount; i++)

{

NSNumber*tickLocation = [NSNumber numberWithInt:i];

NSString *file =[yAxisIcons objectAtIndex:i];

UIImage *icon =[UIImage imageNamed:file];

CPImageLayer*layer; // My custom CPLayer subclass - see code below

CGFloatnativeHeight = 1;

CGFloatnativeWidth = 1;

if (icon) {

layer = [[CPImageLayer alloc] initWithImage:icon];

nativeWidth = 20;//CGImageGetWidth(icon.CGImage);

nativeHeight = 20;//CGImageGetHeight(icon.CGImage);

//layer.contents = (id)icon.CGImage;

if (nativeWidth > biggestCustomIconWidth) {

biggestCustomIconWidth = nativeWidth;

}

}else{

layer= [[CPImageLayer alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];

}

CGRect startFrame = CGRectMake(0.0, 0.0,nativeWidth, nativeHeight);

layer.frame= startFrame;

layer.backgroundColor = [UIColor clearColor].CGColor;

CPAxisLabel *newLabel = [[CPAxisLabel alloc]initWithContentLayer:layer];

newLabel.tickLocation = [tickLocation decimalValue];

newLabel.offset = x.labelOffset +x.majorTickLength; [customLabels addObject:newLabel];

[newLabel release];

[layer release];

}

y.axisLabels = [NSSetsetWithArray:customLabels];

}

CPImageLayer.h

#import "CPLayer.h"

@interface CPImageLayer : CPLayer {

UIImage*_image;

}

-(id)initWithImage:(UIImage *)image; @end

CPImageLayer.m

#import "CPImageLayer.h" #import "CPLayer.h"

@implementation CPImageLayer

-(void)dealloc{

[_imagerelease];

[super dealloc];

}

-(id)initWithImage:(UIImage *)image{

CGRect f =CGRectMake(0, 0, image.size.width, image.size.height);

if (self =[super initWithFrame:f]) {

_image = [imageretain];

}

return self;

}

-(void)drawInContext:(CGContextRef)ctx{

CGContextDrawImage(ctx, self.bounds, _image.CGImage);

}

@end

Jul 22 '11 at 14:01

Lukasz


读书人网 >移动开发

热点推荐