Fit image of random size into a UIWebview (IOS) - ios

I want to fit large image into UIwebview with keeping image ratio same as image view.
How can i do it.?
My code as follows to fit image in Uiwebview.
if image is large then display is not good.
CGFloat screenWidth = self.view.frame.size.width;
CGFloat screenHeight = self.view.frame.size.height;
NSString *htmlString = [NSString stringWithFormat:#"%#", #"<html><head><meta name='viewport' content='user-scalable=yes,width=device-width'></head><body bgcolor='000000'><img src='%#' width='%f' height='%f' style='max-width:200% max-height:200%'></body></html>"];
imageHTML = [[NSString alloc] initWithFormat:htmlString, fileUrl, screenWidth, screenHeight];
[Webview loadHTMLString:imageHTML baseURL:nil];
[imageHTML release];

I have used below code and its working well.
NSString *imageHTML = [[NSString alloc] initWithFormat:#"%#%#%#", #"<!DOCTYPE html>"
"<html lang=\"ja\">"
"<head>"
"<meta charset=\"UTF-8\">"
"<style type=\"text/css\">"
"html{margin:0;padding:0;}"
"body {"
"margin: 0;"
"padding: 0;"
"color: #363636;"
"font-size: 90%;"
"line-height: 1.6;"
"background: black;"
"}"
"img{"
"position: absolute;"
"top: 0;"
"bottom: 0;"
"left: 0;"
"right: 0;"
"margin: auto;"
"max-width: 100%;"
"max-height: 100%;"
"}"
"</style>"
"</head>"
"<body id=\"page\">"
"<img src='",fileUrl,#"'/> </body></html>"];
[wview_contents loadHTMLString:imageHTML baseURL:nil];

To load image in Swift 3.0 from application document directory in a UIWebView with his expected ratio -
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(imageName)
let fullHTML = "<!DOCTYPE html>" +
"<html lang=\"ja\">" +
"<head>" +
"<meta charset=\"UTF-8\">" +
"<style type=\"text/css\">" +
"html{margin:0;padding:0;}" +
"body {" +
"margin: 0;" +
"padding: 0;" +
"color: #363636;" +
"font-size: 90%;" +
"line-height: 1.6;" +
"background: black;" +
"}" +
"img{" +
"position: absolute;" +
"top: 0;" +
"bottom: 0;" +
"left: 0;" +
"right: 0;" +
"margin: auto;" +
"max-width: 100%;" +
"max-height: 100%;" +
"}" +
"</style>" +
"</head>" +
"<body id=\"page\">" +
"<img src='\(path)'/> </body></html>"
imgWbView.loadHTMLString(fullHTML, baseURL: nil)
}

Set your WebView page to scale fit:
[webView setScalesPageToFit:YES];
EDIT:
Here check these two lines also
CGFloat screenWidth = self.view.frame.size.width;
CGFloat screenHeight = self.view.frame.size.height;
If you know what size you want them pass static values here, will fix your problem.
e.g.
CGFloat screenWidth = 300;
CGFloat screenHeight = 300;

The following code snippet may help you
NSString *fontString = #"<!DOCTYPE html><html>\
<head>\
<style>\
img{";
NSString *imageDimensionsStr = [NSString stringWithFormat:#"max-width: %fpx; max-height: %fpx;}",self.view.frame.size.width - 50.0f, self.view.frame.size.height/2];
fontString =[fontString stringByAppendingString:imageDimensionsStr];
fontString = [fontString stringByAppendingString:#"</style></head><body>"];
fontString = [[fontString stringByAppendingString:htmlString] stringByAppendingString:#"</body></html>"];
[webView loadHTMLString:fontString baseURL:nil];
The above code will resize the width and height of the image according to view dimension. You can change according to your requirement.

This works for me to fit the image size within width of device for Swift 5
Helpful with dynamic html from server
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
let fontAdjust = "var style = document.createElement('style');style.innerHTML = 'body { -webkit-text-size-adjust: none; }';document.getElementsByTagName('head')[0].appendChild(style);"
let imgAdjust = "var style = document.createElement('style');style.innerHTML = 'img { display: inline;height: auto;max-width: 100%; }';document.getElementsByTagName('head')[0].appendChild(style);"
webKitView.evaluateJavaScript(imgAdjust)
webKitView.evaluateJavaScript(fontAdjust)
webKitView.evaluateJavaScript(imgAdjust)
}

Related

Stop running the program because WebView

My program runs successfully and the simulator runs, but all at once end.
An error occurs on this:
mWebView.LoadDataWithBaseURL("", str1, "text/html", "utf-8", null);
WebView mWebView = FindViewById<WebView>(Resource.Id.webView1);
String str1 =
"<html>" +
"<head>" +
"<style type='text/css'>" +
"#font-face {font-family:SFont; src:url('file:///android_asset/fonts/MyFont.TTF');}" +
"#font-face {font-family:TFont; src:url('file:///android_asset/fonts/times.ttf');}" +
"Ptext {" +
"font-family: SFont;" +
"font-size: 19px;" +
"text-align: justify;" +
"}" +
"Etext {" +
"font-family: TFont;" +
"font-size: 13px;" +
"text-align: justify;" +
"}" +
"body {" +
"text-align: justify;" +
"}" +
"</style>" +
"</head>" +
"<body dir = rtl>" +
"<font style='opacity:0.79'>" +
"<font color='white'>" +
"<Ptext>" + "Hello Hello" + " " + "</Ptext>" +
"<Etext>" + "Hello Hello" + "</Ptext>" +
"</font>" +
"</body>" +
"</html>";
mWebView.SetBackgroundColor(Color.ParseColor("#00000000"));
mWebView.LoadDataWithBaseURL("", str1, "text/html", "utf-8", null);
ERRORS:
[ERROR:gl_surface_egl.cc(327)] No suitab EGL configs found.
[ERROR:gl_surface_egl_android.cc(23)] GLSurfaceEGL::InitializeOneOff faild.
[Error:browser_main_lppo.cc(698)]GLSurdace::InitializeOneOff faild
[FATAL:gl_Surface_android.cc(58)] Check failed: kGLImplementationNone != GetGLImplementation()(0 vs. 0)

HTML hyperlink to NSAttributedString did not style

I am attempting to create NSAttributedString from given HTML string, with paragraph and hyperlink. Everything is fine, except styling hyperlink.
My code to style looks like:
func htmlAttributed() -> NSAttributedString? {
do {
let htmlCSSString = "<style>" +
"* {" +
"font-size: 12px !important;" +
"color: #9D9B98 !important;" +
"}" +
"p" +
"{" +
"font-size: 12px !important;" +
"color: #9D9B98 !important;" +
"font-family: Helvetica !important;" +
"}" +
"a" +
"{" +
"font-size: 12px !important;" +
"color: hotpink !important;" +
"font-family: Helvetica !important;" +
"}" +
"a:link" +
"{" +
"text-decoration: none !important;" +
"color: hotpink !important;" +
"}" +
"a:visited" +
"{" +
"text-decoration: none !important;" +
"}" +
"</style> \(self)"
guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
and it giving great result when I open it in website. But translation to NSAttributedString works only for p mark, not for hyperlink.
For testing I use this part of code
<p>This is not a link <b><a class='test' href='test' target='_blank'>This is a link</a></b></p>
On w3c playground I have:
On iPhone I've got:
If you're using a UILabel, try using UITextView instead and change link colors using linkTextAttributes. This way your links will also be tappable.
textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemPink]

Is .heic image supported by WKWebView on iOS 11?

I tried to load a .heic image using WKWebView.loadFileURL on iOS 11.4 but got a blank page.
(I am sure the url is right as I can preview it in xcode)
Convert "heic" image to jpeg data and load with the help of html as:
if fileExtension == "heic" {
guard let fileData = fileData,
let image = UIImage(data: fileData),
let jpegData = image.jpegData(compressionQuality: 1.0)
else {
return
}
let base64JPG = jpegData.base64EncodedString(options: .lineLength64Characters)
let htmlImgTag = "<img src=\"data:image/jpeg;base64, " + base64JPG + "\" alt=\"" + fileUrl.lastPathComponent + "\" />"
let imageHTML = "<!DOCTYPE html>" +
"<html lang=\"ja\">" +
"<head>" +
"<meta charset=\"UTF-8\">" +
"<style type=\"text/css\">" +
"html{margin:0;padding:0;}" +
"body {" +
"margin: 0;" +
"padding: 0;" +
"color: #363636;" +
"font-size: 90%;" +
"line-height: 1.6;" +
"background: black;" +
"}" +
"img{" +
"position: absolute;" +
"top: 0;" +
"bottom: 0;" +
"left: 0;" +
"right: 0;" +
"margin: auto;" +
"max-width: 100%;" +
"max-height: 100%;" +
"}" +
"</style>" +
"</head>" +
"<body id=\"page\">" +
"\(htmlImgTag)" +
"</body></html>"
webView.loadHTMLString(imageHTML, baseURL: nil)
}

how to get youtuber video information in youtube api v3..?

i am working on a youtube based api website and want to get the complete information of a video.
i am doing this as
<?php $JSON_Data = json_decode(file_get_contents("https://gdata.youtube.com/feeds/api/videos/9Xhat18gkLw?v=2&alt=json")); ?>
and getting data using this method
channel is:<?php echo $JSON_Data->entry->author[0]->name->{'$t'}."<br>"; ?>description is:<?php echo $JSON_Data->entry->{'media$description'}->$t."<br>"; ?>published time:<?php echo $JSON_Data->entry->published->{'$t'}."<br>"; ?>duration time:<?php echo $JSON_Data->{'yt$duration'}->seconds."<br>"; ?>image link:<?php echo $JSON_Data->{'media$thumbnail'}[2]->url."<br>"; ?>title is:<?php echo $JSON_Data->entry->title->{'$t'}."<br>"; ?>
but i am successful in getting a few information like title, channel name and published time
channel is:Naatsworld
description is:
published time:2011-08-27T01:32:36.000Z
duration time:
image link:
title is:Owais Raza Qadri - Main So Jaon Ya Mustafa Kehte Kehte (Full Video Naat Album)!!!
i also want to get video duration, description and image link
please help me how to do this
See if this helps you lot :
<script type="text/javascript">
function youtubeFeedCallback(data) {
document.writeln('<img src="' + data.entry["media$group"]["media$thumbnail"][0].url + '" width="' + data.entry["media$group"]["media$thumbnail"][0].width + '" height="' + data.entry["media$group"]["media$thumbnail"][0].height + '" alt="Default Thumbnail" align="right"/>');
document.writeln('<b>Title:</b> ' + data.entry["title"].$t + '<br/>');
document.writeln('<b>Author:</b> ' + data.entry["author"][0].name.$t + '<br/>');
document.writeln('<b>Published:</b> ' + new Date(data.entry["published"].$t.substr(0, 4), data.entry["published"].$t.substr(5, 2) - 1, data.entry["published"].$t.substr(8, 2)).toLocaleDateString() + '<br/>');
document.writeln('<b>Duration:</b> ' + Math.floor(data.entry["media$group"]["yt$duration"].seconds / 60) + ':' + (data.entry["media$group"]["yt$duration"].seconds % 60) + ' (' + data.entry["media$group"]["yt$duration"].seconds + ' seconds)<br/>');
document.writeln('<b>Rating:</b> ' + new Number(data.entry["gd$rating"].average).toFixed(1) + ' out of ' + data.entry["gd$rating"].max + '; ' + data.entry["gd$rating"].numRaters + ' rating(s)' + '<br/>');
document.writeln('<b>Statistics:</b> ' + data.entry["yt$statistics"].favoriteCount + ' favorite(s); ' + data.entry["yt$statistics"].viewCount + ' view(s)' + '<br/>');
document.writeln('<br/>' + data.entry["media$group"]["media$description"].$t.replace(/\n/g, '<br/>') + '<br/>');
document.writeln('<br/>Watch on YouTube');
}
</script>
View demo

Phonegap Geolocalisation application crashes

I'm trying to get current localisation using phonegap javascript api. Here is a sample code taken from phonegap website:
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + new Date(position.timestamp) + '<br />';
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
If I remove geolocalisation code, the application works well.
Any ideas ?
Thanks in advance,
If you are seeing the error in Android, you want to add the enableHighAccuracy flag:
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
I have just tried it on PhoneGap 1.4.1, iOS Simulator 5.0 and it works fine.
What kind of error are you getting ?
if you are trying it on android device then altitudeAccuracy property is not support by Android devices, it will always return null.

Resources