2012-07-31 24 views
1

我試圖在圖像中獲得突出的顏色。最初,我試圖獲取this post中的顏色集。但我的客戶不滿意它,因爲它只返回平均顏色集而不是確切的顏色。因此,現在我試圖通過this link.中找到的邏輯來獲得主色設置。但問題是代碼是在jQuery和JavaScript中。 似乎它很容易在網上實現,因爲代碼很簡單,因爲在我的iOS應用程序中集成jquery-javascript項目

myImage = $('#myImage'); 
dominantColor = getDominantColor(myImage); 
paletteArray = createPalette(myImage, 10); // 2nd argument sets # of colors in palette 

我上網如何在iOS的執行JS和參考做給this linkthis link,做了如下

[_webView loadHTMLString:@"<script src=\"color-thief.js\"></script>" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]]; 

    NSString * imgName = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"jpg"]; 
// UIImage * img = [UIImage imageNamed:imgName]; 
    int colorCount = 9; 

    NSString *function1 =[[NSString alloc] initWithFormat: @"createPalette(%@, %d)", imgName, colorCount]; 
// NSString *function2 = [[NSString alloc] initWithFormat: @"getAverageRGB(%@)", imgName]; 
    NSString *result = [_webView stringByEvaluatingJavaScriptFromString:function1]; 

    NSLog(@"%@ result %@", result, [_webView stringByEvaluatingJavaScriptFromString:funcion1]); 

但我無法得到任何結果。其無效。我錯過了什麼?有人能指出我出了什麼問題嗎?任何及時的幫助表示讚賞。提前致謝。

回答

0

你確定你的網頁沒有加載jQuery庫(從磁盤或在線)嗎?

您可以使用safari調試webview,以檢查在模擬器或設備中打開webview時發生了什麼問題。 Here's a guide from apple讓你開始。

0

我有同樣的問題。您需要一些不同的功能,在getPalette的末尾明確製作HTMLImageElement.toString()。還有一些奇怪的Safari行爲,它只適用於第二次拍攝:

let function = "var colorThief = new ColorThief(); var image = new Image(); image.src='\(imgName)'; colorThief.getPalette(image, 5).toString();" 

let result1 = self.webView.stringByEvaluatingJavaScriptFromString(function)! 
// for some reason result1 is always empty, but if we evaluate the same function second time after some time interval we will get the results. 

sleep(1) 

let result2 = self.webView.stringByEvaluatingJavaScriptFromString(function)! 
// result2 is string of rgb components separated by commas