iOS 利用chart.min.js画表格(其实是iOS与javascript和html的结合)

本文介绍了如何在iOS应用中结合UIWebView和javascript的chart.min.js库来展示图表。通过创建HTML页面并利用javascript画图,然后在iOS中加载和执行javascript代码,实现了将数据以图表形式展示在app界面上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做一个基于genecard的iOS app,其中要把数据以图表的形式展现出来,所以在网上学习了一下用UIWebView的用法,用javascript在html页面上画好图再展现在app界面上。

当然我不会每一样图都演示一遍,我只演示一种图形,好了,贴代码。

1.首先肯定是要准备一个html页面让javascript在上面画图啰。

<!doctype html>

<html>

<head>

<title></title>

<metaname = "viewport" content ="initial-scale = 1, user-scalable = no">

<style>

</style>

</head>

<bodystyle="background-color: transparent;">

//待会就在这里画图

<canvas></canvas><br/>

        <a id="callback"href="callback:whatever"></a>

        <script src="chart.min.js"></script>

</body>

</html>

2.看.js文件,看看画每一种图形所要的数据是什么,然后写一个个model,但我们可以抽取每种图形所要的数据,生产一个父类再让其他的去继承他(但我们这就不那么细了)。

//

//  TWRDataSet.h

//  HILab1.0

//

//  Created by dengwt on 2017/2/10.

//  Copyright © 2017 dengwt. All rights reserved.

//


#import <Foundation/Foundation.h>

#import "TWRChart.h"

#import <UIKit/UIKit.h>



@interface TWRDataSet : NSObject


@property (strong,nonatomic) UIColor *fillColor;

@property (strong,nonatomic) UIColor *strokeColor;

@property (strong,nonatomic) UIColor *pointColor;

@property (strong,nonatomic) UIColor *pointStrokeColor;

@property (copy,nonatomic) NSMutableArray *dataPoints;

//生产model实例的方法

- (instancetype)initWithDataPoints:(NSArray *)dataPoints

                         fillColor:(UIColor *)fillColor

                       strokeColor:(UIColor *)strokeColor

                        pointColor:(UIColor *)pointColor

                  pointStrokeColor:(UIColor *)pointStrokeColor;


- (instancetype)initWithDataPoints:(NSArray *)dataPoints

                         fillColor:(UIColor *)fillColor

                       strokeColor:(UIColor *)strokeColor;

- (instancetype)initWithDataPoints:(NSArray *)dataPoints;

@end



//

//  TWRDataSet.m

//  HILab1.0

//

//  Created by dengwt on 2017/2/10.

//  Copyright © 2017 dengwt. All rights reserved.

//


#import "TWRDataSet.h"


@implementation TWRDataSet


- (instancetype)initWithDataPoints:(NSArray *)dataPoints {

    // Default color: light gray

    UIColor *fillColor = [UIColorcolorWithRed:220/255.0fgreen:220/255.0fblue:220/255.0falpha:0.5];

    UIColor *strokeColor = [UIColorcolorWithRed:220/255.0fgreen:220/255.0fblue:220/255.0falpha:1.0];

    UIColor *pointColor = [UIColorcolorWithRed:220/255.0fgreen:220/255.0fblue:220/255.0falpha:1.0];

    UIColor *pointStrokeColor = [UIColorwhiteColor];

    self = [selfinitWithDataPoints:dataPointsfillColor:fillColor strokeColor:strokeColor pointColor:pointColor pointStrokeColor:pointStrokeColor];


    returnself;

}


- (instancetype)initWithDataPoints:(NSArray *)dataPoints

                         fillColor:(UIColor *)fillColor

                       strokeColor:(UIColor *)strokeColor {

    UIColor *pointColor = strokeColor;

    UIColor *pointStrokeColor = strokeColor;

    self = [selfinitWithDataPoints:dataPointsfillColor:fillColor strokeColor:strokeColor pointColor:pointColor pointStrokeColor:pointStrokeColor];

    

    returnself;

}


- (instancetype)initWithDataPoints:(NSArray *)dataPoints

                         fillColor:(UIColor *)fillColor

                       strokeColor:(UIColor *)strokeColor

                        pointColor:(UIColor *)pointColor

                  pointStrokeColor:(UIColor *)pointStrokeColor {

    self = [superinit];

    if (self) {

        _dataPoints = dataPoints.mutableCopy;

        _fillColor = fillColor;

        _strokeColor = strokeColor;

        _pointColor = pointColor;

        _pointStrokeColor = pointStrokeColor;

    }

    returnself;

}


@end

3.编写图形类。

#import <Foundation/Foundation.h>

@class TWRDataSet;


@interface TWRBarChart : NSObject


@property (copy,nonatomic) NSMutableArray *labels;

@property (copy,nonatomic) NSMutableArray *dataSets;

@property (assign,nonatomic) BOOL animated;


- (instancetype)initWithLabels:(NSArray *)labels

                      dataSets:(NSArray *)dataSets

                      animated:(BOOL)animated;


@end


//

//  TWRBarChart.m

//  HILab1.0

//

//  Created by dengwt on 2017/2/10.

//  Copyright © 2017 dengwt. All rights reserved.

//


#import "TWRBarChart.h"


@implementation TWRBarChart


- (instancetype)initWithLabels:(NSArray *)labels

                      dataSets:(NSArray *)dataSets

                      animated:(BOOL)animated {

    self = [superinit];

    if (self) {

//由NSArray生产NSMutableArray

        _labels = labels.mutableCopy;

        _dataSets = dataSets.mutableCopy;

        _animated = animated;

    }

    returnself;

}


@end


4.重点来了,写一个生产图形的生成者,这里的技术难点是怎么将图形类里面的数据传到javascript里面然后根据这些数据生成图形。我们这里使用UIWebView的

stringByEvaluatingJavaScriptFromString方法,里面我们将生产图形分成两个步骤,一是根据图形类里面的数据生成相应的javascript语句,二是打开html文件,执行javascript语句生成相应的文件,贴代码。

+ (NSString *)buildBarChartStringForElement:(TWRBarChart *)element {

    __blockNSString *retString;

//取出canvas,待会往里面画图

    retString = @"var context = document.getElementById(\"canvas\").getContext(\"2d\"); var barChartData = { labels:[";

    TWRBarChart *barChart = (TWRBarChart *)element;

//根据TWRBarChart的数据生成相应的javascript语句

    [barChart.labelsenumerateObjectsUsingBlock:^(NSString *label,NSUInteger idx, BOOL *stop) {

        retString = [retString stringByAppendingString:[NSStringstringWithFormat:@"\"%@\"", label]];

        if (idx != barChart.labels.count -1) {

            retString = [retString stringByAppendingString:@","];

        } else {

            // close the array

            retString = [retString stringByAppendingString:@"], datasets:["];

        }

    }];

    

    [barChart.dataSetsenumerateObjectsUsingBlock:^(TWRDataSet *dataset,NSUInteger idx, BOOL *stop) {

        NSString *fillColorString = [datasetfillColorString];

        NSString *strokeColorString = [datasetstrokeColorString];

        NSString *pointColorString = [datasetpointColorString];

        NSString *pointStrokeColorString = [datasetpointStrokeColorString];

        NSString *dataString = [datasetdataString];

        retString = [retString stringByAppendingString:[NSStringstringWithFormat:@"{fillColor:%@,strokeColor:%@,pointColor:%@,pointStrokeColor:%@,data:%@}", fillColorString, strokeColorString, pointColorString, pointStrokeColorString, dataString]];

        if (idx != barChart.dataSets.count -1) {

            retString = [retString stringByAppendingString:@","];

        } else {

            retString = [retString stringByAppendingString:@"]};"];

        }

    }];

    

    retString = [retString stringByAppendingString:[NSStringstringWithFormat:@"var options = {animation:%@};", barChart.animated ?@"true" : @"false"]];

//这句javascript语句是生成图形的

    retString = [retString stringByAppendingString:@"var myLine = new Chart(context).Bar(barChartData,options);"];

    return retString;

}


5.UIwebview加载html文件在里面执行javascript语句画图
//加载html文件

- (void)loadIndex {

    NSError *error;

    // Load index.html

    NSString *htmlString = [NSStringstringWithContentsOfFile:_htmlFilePathencoding:NSUTF8StringEncodingerror:&error];

    

    // Set canvas size according to frame dimensions. Leave space for labels at the bottom.

    NSString *canvasString = [NSStringstringWithFormat:@"<canvas id=\"canvas\" height=\"%d\" width=\"%d\"></canvas>", (int)CGRectGetHeight(self.frame)-20, (int)CGRectGetWidth(self.frame) - 10];

    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<canvas></canvas>"withString:canvasString];

    

    // Load it!

    [selfloadHTMLString:htmlStringbaseURL:[[NSBundlemainBundle] bundleURL]];

}

//画图

- (void)loadBarChart:(TWRBarChart *)barChart {

    if ([barChartisKindOfClass:[TWRBarChartclass]] ) {

        _jsFileString = [TWRChartBuilderbuildChartWithElement:barChart];

        [selfstringByEvaluatingJavaScriptFromString:_jsFileString];

        [selfloadIndex];

    } else {

        NSException *exception = [NSExceptionexceptionWithName:@"TWRChartInvalicChartElement"

                                                        reason:@"The element object provided to the chart view is not a valid bar chart."

                                                       userInfo:nil];

        [exception raise];

    }

}

6.在UIviewcontroller里面传入数据然后画图

- (void)loadBarChart {

    // Build chart data

    TWRDataSet *dataSet1 = [[TWRDataSetalloc] initWithDataPoints:@[@10,@15, @5,@15, @5]

                                                        fillColor:[[UIColororangeColor] colorWithAlphaComponent:0.5]

                                                      strokeColor:[UIColororangeColor]];

    

    TWRDataSet *dataSet2 = [[TWRDataSetalloc] initWithDataPoints:@[@5,@10, @5,@15, @10]

                                                        fillColor:[[UIColorredColor] colorWithAlphaComponent:0.5]

                                                      strokeColor:[UIColorredColor]];

    

    NSArray *labels =@[@"A",@"B", @"C",@"D", @"E"];

    TWRBarChart *bar = [[TWRBarChartalloc] initWithLabels:labels

                                                  dataSets:@[dataSet1, dataSet2]

                                                  animated:YES];

    // Load data

    [_chartViewloadBarChart:bar];

}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值