iphone - UIWebview 操作 SVG 'on the fly'

标签 iphone html ios uiwebview svg

我想知道如何操作已加载到 UIWebview 中的 SVG 文件。目前我正在将 SVG 文件加载到 HTML 文件中,然后将其加载到 UIWebview 中。我认为您会使用 Javascript 来执行此操作,但不确定具体是如何进行的。理想情况下,我希望能够在 iPad 应用程序中即时操作 SVG。我知道您可以将代码“注入(inject)”到 UIWebview 中,但我的尝试没有成功。清澈如泥?好吧,也许一些代码会有所帮助。

以下是我如何将 html 文件加载到 View Controller .m 文件内的 UIWebview 中:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    NSString*  path    = [[NSBundle mainBundle] pathForResource:@"SVG" ofType:@"html"];
    NSString*  content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    webView = [UIWebView new];
    webView.frame = CGRectMake(0, 0, 1024, 768);
    webView.dataDetectorTypes = UIDataDetectorTypeAll;
    webView.userInteractionEnabled = YES;
    [webView loadHTMLString:content baseURL:[[NSBundle mainBundle] bundleURL]];

    [self.view addSubview:webView];
    [webView release];
}

以下是加载到 UIWebview 中的 html 文件内的代码:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>SVG</title>
  </head>
  <body>
    <object id="circle" data="Circle.svg" width="250" height="250" type="image/svg+xml"/> 
  </body>
</html>

...最后是 SVG 文件中的代码:

<svg xmlns="http://www.w3.org/2000/svg">
<circle id="redcircle" cx="200" cy="50" r="50" fill="red" />
</svg>

这会在 UIWebview 中创建一个漂亮的红色小圆圈。现在我希望能够在 View Controller .m 文件中快速操作圆圈。例如,当用户触摸iPad屏幕时,将填充颜色属性更改为绿色。这可能吗?

我希望这一切都有道理。有点复杂。但最终我想做的是在 HTML 框架中使用 SVG 动态创建图形并将其显示在 UIWebview 中。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

您可以在页面首次加载后的任何时候将其传递给 webView 上的 stringByEvaluatingJavaScriptFromString 来执行任意 Javascript - 就像响应触摸事件一样。

因此,如果查找 SVG 对象并更改颜色的 Javascript 看起来像这样(YMMV,尚未实际测试过):

var path=document.getElementById("circle").getSVGDocument().getElementById("redcircle");path.style.setProperty("fill", "#00FF00", "");

您可以通过以下方式执行它:

NSString *string = @"var path=document.getElementById('circle').getSVGDocument().getElementById('redcircle');path.style.setProperty('fill', '#00FF00', '');";
[webView stringByEvaluatingJavaScriptFromString:string];

关于iphone - UIWebview 操作 SVG 'on the fly',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6991828/

相关文章:

iphone - Guard Malloc 立即发现 EXC_BAD_ACCESS 错误。为什么不一直使用呢?

html - 如何使用 html 和 css 在卡片上创建背景框架

html - 具有自动宽度的相对 DIV

php - 错误: Strict Standards: Only variables should be passed by reference? [duplicate]

android - 从移动浏览器分析页面加载时间的好方法

iphone - 更改搜索栏的背景图片

iPhone 标签栏应用程序不旋转

ios - 如何使用 Apple 提供的图标

ios - Swift 3 UIView 动画

ios - bundle 无效——Info.plist 中的 CFBundleVersion 和 CFBundleShortVersionString 必须包含更高版本——但它们确实如此