本文整理在專案中實際使用 Core Plot 繪製圖表時累積的實用技巧,並附上 iOS 記憶體優化的排查經驗。
graph.plotAreaFrame.paddingLeft += 5; graph.plotAreaFrame.paddingTop += 5; graph.plotAreaFrame.paddingRight += 5; graph.plotAreaFrame.paddingBottom += 17.5;
[self setAllowPinchScaling:NO];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromFloat(1)]; plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromFloat(1)]; plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(1) length:CPTDecimalFromFloat(1)]; plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromFloat(2)];
x.axisLabels = [self buildLabelTitle];
x.labelingPolicy = CPTAxisLabelingPolicyNone; // 設為此 Policy 後,label 與 tick 都需自行繪製
x.minorTickLocations = [NSSet setWithArray:locationLabels];
- (NSMutableSet *)buildLabelTitle
{
NSMutableSet *newAxisLabels = [NSMutableSet set];
CPTMutableTextStyle *textStyleB = [CPTMutableTextStyle textStyle];
textStyleB.color = [CPTColor colorWithComponentRed:CPTFloat((float)0x09/0xFF)
green:CPTFloat((float)0x31/0xFF)
blue:CPTFloat((float)0x4A/0xFF)
alpha:CPTFloat(1.0)];
int n = 1;
for (NSUInteger i = 30; i > 0; i--) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:@"這裡是內容" textStyle:textStyleB];
newLabel.tickLocation = CPTDecimalFromUnsignedInteger(n++);
newLabel.offset = 5;
[locationLabels addObject:[NSNumber numberWithFloat:(n - 1) - 0.25]];
[locationLabels addObject:[NSNumber numberWithFloat:(n - 1) + 0.25]];
[newAxisLabels addObject:newLabel];
[newLabel release];
}
return newAxisLabels;
}
[bar1graph reloadData];
case CPTBarPlotFieldBarTip:
number = [[[m_SO2OnlineC objectAtIndex:index] valueForKey:@"y"] doubleValue] / MAX_data;
break;
這裡之所以要記錄 MAX_data,是因為最好使用「真實數據的相對比例」來繪製。否則當數值很大時,會拖垮 Core Plot 的效能,導致圖形載入緩慢。
[self performSelector:@selector(initPlotData) withObject:nil afterDelay:0.2];
NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:-i]; NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:[NSDate date] options:0];
for (UIView *sbView in scrvBg.subviews) {
[sbView removeFromSuperview];
}
取得子檢視的小技巧:[subView setTag:300]; subView = [self.view viewWithTag:300];self.my_arr = [[NSArray alloc] init]; // 錯誤! NSArray *tmpArr = [[NSArray alloc] init]; self.my = tmpArr; [tmpArr release]; // 正確