开发者

Invert colors in UIWebView or UITextView

I was wondering if anyone knew if there was an easy way to invert the colors of a UIWebView or UITextView. I know it is possible to invert all on your iPhone, but I do not want the user to have to do that, they should be able to with one click in app, invert the colors so that if it is a low light sit开发者_StackOverflow社区uation, reading something will be easier and less intrusive to people around the user.

Thanks for any help!


Here is one way I've inverted colors in a UIWebView (in the past) by injecting javascript.

First...

#define invertJS @"function load_script(src,callback){var s=document.createElement('script');s.src=src;s.onload=callback;document.getElementsByTagName('head')[0].appendChild(s);}function invertColors(){var colorProperties=['color','background-color'];$('*').each(function(){var color=null;for(var prop in colorProperties){prop=colorProperties[prop];if(!$(this).css(prop))continue;color=new RGBColor($(this).css(prop));if(color.ok){$(this).css(prop,'rgb('+(255-color.r)+','+(255-color.g)+','+(255-color.b)+')');}color=null;}});}load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js',function(){if(!window.jQuery)load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',invertColors);else invertColors();})"

And then when your webview finishes loading

- (void)webViewDidFinishLoad:(UIWebView *)webview{
[webview stringByEvaluatingJavaScriptFromString:invertJS];}


For a UITextView you can set the text color and background color attributes, I know from there you could set up a button to switch between white back/black text and black back/white text. Unfortunately, I do not see any similar attributes for UIWebView.

See iOS Documentation for UITextViews and UIWebViews.

Also when passing colors to these attributes, you can use Hex values instead of Apple's preset colors. In this way you could call the hex value of the attribute, invert it with any number of formulas, and pass the new hex value back to the attribute.

Inverting a Hex color, put simply:

// maximum hex value is FFFFFF, so
newHex = FFFFFF - oldHex;


To get the ARGB components of any UIColor, you can use the code provided in this answer:

Extracting rgb from UIColor

You can then "invert" the colors (sort of) by subtracting the r, g and b components (but not the a) from 1.0, and then using these modified components to produce a new color, like so:

r = 1.0 - r;
g = 1.0 - g;
b = 1.0 - b;
UIColor newColor = [UIColor colorWithRed:r green:g blue:b alpha:1.0];


I ended up just making two separate files on my server. One that is inverted and one that is regular. There does not seem to be anything in core graphics at least that I could find that would easily do this and to be honest HTML or CSS are definitely not my strong points. Still if anyone has a simpler solution for this I am more than interested in a good idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜