Is it possible to tell a Windows 8.1 app not to scale up specific elements? - xaml

I am referencing external image urls for the source property of an image element in my app.
I have 3 versions of the image at 100, 140 and 180 scales e.g.
myimage.scale-100.jpg
myimage.scale-140.jpg
myimage.scale-180.jpg
If the images lived in the app you would normally put the source like the following and Windows works out which image to load based on the resolution scale of the device:
ms-appx:///Assets/Images/myimage.jpg
However as my 3 images live externally I am having to work out the resolution scale and then build up the correct source string so that the correct image is loaded e.g:
http://www.mywebsite.com/myimage.scale-180.jpg
This works, however, windows is taking my image e.g. the 180 scale one myimage.scale-180.jpg, and then scaling it up by a further 180%, it doesn't know that I have loaded an image at the correct 180% scale already and that it doesn't need to scale it up!
Is there a way of telling it not to scale up specific image elements?
Update (added code):
The xaml image element:
<Image Source="{Binding Image, Converter={StaticResource ImageToExternalImagePathConverter}}" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="None" />
The converter used on the image element to determine the external image path (it works out the scale and uses the binding to build up the correct string).
public object Convert(object value, Type targetType, object parameter, string language)
{
ResolutionScale resolutionScale = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().ResolutionScale;
string ImageScale = ".scale-100";
switch (resolutionScale)
{
case ResolutionScale.Scale140Percent:
ImageScale = ".scale-140";
break;
case ResolutionScale.Scale180Percent:
ImageScale = ".scale-180";
break;
}
//builds up the correct string e.g. http://www.mywebsite.com/myimage.scale-180.jpg
string externalPath = "http://www.mywebsite.com/" + (string)value + ImageScale + ".jpg";
return externalPath;
}
Update(added reference):
To further explain what I am currently doing see this link:
http://msdn.microsoft.com/en-us/library/windows/apps/hh465362.aspx
Manually load images based upon scale percentage at runtime If your
app is loading images at runtime using code, for example if you use
DirectX directly, not XAML or HTML to create your UI, use the
DisplayProperties.ResolutionScale property to determine the scale and
manually load images based upon scale percentage.
So that's what I am doing, but the problem is that Windows is scaling up the UI as it should to 140% or 180%, and that includes my manually loaded image. So if I manually load in an image that is already sized at 140%, it gets scaled up by Windows anyway and it DOES get physically bigger. If the images lived in the app package this problem wouldnt exist because Windows recognises the filename identifiers and doesnt scale them up (see below)
Use resource loading for bitmap images in the app package For bitmap
images stored in the app package, provide a separate image for each
scaling factor(100%, 140%, and 180%), and name your image files using
the "scale" naming convention described below. Windows loads the right
image for the current scale automatically.
How can I replicate the same behavior from Windows for images that live in the app package but for images that are external to the app and are loaded manually? Logically at the point at which I load the image in (code), I want to say to Windows, this image is already scaled correctly, don't upscale it by the resolution factor.

Try sizing grip property to false

Related

Cannot find the exact eror sometimes showing Adapter not attached sometimes cannot find memetrack [duplicate]

I'm running Ubuntu 16.04. And on Android Studio when I try to run my application in the emulator I get the following error:
FATAL EXCEPTION: main
Process: project name here, PID: 2528
java.lang.RuntimeException: Canvas: trying to draw too large(216090000bytes) bitmap.
at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:528)
at android.widget.ImageView.onDraw(ImageView.java:1316)
at android.view.View.draw(View.java:17185)
at android.view.View.updateDisplayListIfDirty(View.java:16167)
at android.view.View.draw(View.java:16951)
at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513)
at android.view.View.updateDisplayListIfDirty(View.java:16162)
at android.view.View.draw(View.java:16951)
at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513) at
etc...
I did have to run through some hoops to get my emulator working however, needed to create a sym-link so I can run the emulator on AMD. Not sure if this is part of the problem. And for the life of me I cannot figure why it continues to do this. In my group there are others who emulate the project just fine on the same emulated phone and SDK.
Move your image in the (hi-res) drawable to drawable-xxhdpi. But in app development, you do not need to use large image. It will increase your APK file size.
The solution is to move the image from drawable/ folder to drawable-xxhdpi/ folder, as also others have mentioned.
But it is important to also understand why this somewhat weird suggestion actually helps:
The reason is that the drawable/ folder exists from early versions of android and is equivalent to drawable-mdpi. When an image that is only in drawable/ folder is used on xxhdpi device, the potentially already big image is upscaled by a factor of 3, which can then in some cases cause the image's memory footprint to explode.
This solution worked for me.
Add these lines in your Manifest application tag
android:largeHeap="true"
android:hardwareAccelerated="false"
I had the same problem.
If you try to upload an image that is too large on some low resolution devices, the app will collapse.
You can make several images of different sizes (hdpi, xxdpi and more) or simply use an external library to load images that solve the problem quickly and efficiently.
I used Glide library (you can use another library like Picasso).
panel_IMG_back = (ImageView) findViewById(R.id.panel_IMG_back);
Glide
.with(this)
.load(MyViewUtils.getImage(R.drawable.wallpaper)
.into(panel_IMG_back);
This issue can be resolved by 3 methods as follows:
Method 1:
By adding image into a res/drawable-nodpi folder (By doing this it will not pre-scale your image).
Method 2:
Generate all dpi(hdpi,ldpi,mdpi,xhdpi,xxhdpi,xxxhdpi) of image and add to drawable folder. (This process will increase APK size).
Method 3:
Add image to drawable/drawable-xxhdpi folder.
All these methods are verified.
Turns out the problem was the main image that we used on our app at the time. The actual size of the image was too large, so we compressed it. Then it worked like a charm, no loss in quality and the app ran fine on the emulator.
For this error was like others said a big image(1800px X 900px) which was in drawable directory, I edited the image and reduced the size proportionally using photoshop and it worked...!!
If you don't want your image to be pre-scaled you can move it to the res/drawable-nodpi/ folder.
More info: https://developer.android.com/training/multiscreen/screendensities#DensityConsiderations
if you use Picasso change to Glide like this.
Remove picasso
Picasso.get().load(Uri.parse("url")).into(imageView)
Change Glide
Glide.with(context).load("url").into(imageView)
More efficient Glide than Picasso draw to large bitmap
I also had this issue when i was trying to add a splash screen to the android app through the launch_backgrgound.xml . the issue was the resolution. it was too high so the images memory footprint exploded and caused the app to crash hence the reason for this error. so just resize your image using a site called nativescript image builder so i got the ldpi,mdpi and all the rest and it worked fine for me.
I just created directory drawable-xhdpi(You can change it according to your need) and copy pasted all the images to that directory.
This can be an issue with Glide. Use this while you are trying to load to many images and some of them are very large:
Glide.load("your image path")
.transform(
new MultiTransformation<>(
new CenterCrop(),
new RoundedCorners(
holder.imgCompanyLogo.getResources()
.getDimensionPixelSize(R.dimen._2sdp)
)
)
)
.error(R.drawable.ic_nfs_default)
.into(holder.imgCompanyLogo);
}
Try using an xml or a vector asset instead of a jpg or png.
The reason is quite obvious in the exception name itself i.e. the resolution of the resource is too large to render.
You can png to xml using online tools like https://svg2vector.com/ OR add your image to drawable-xxhdpi folder.
Solution for Picasso is add Transformation for resize image.
class ResizeTransformation(private val maxSize: Int) : Transformation {
override fun transform(source: Bitmap?): Bitmap? {
var result:Bitmap? = null
if (source != null) {
var width = source.width
var height = source.height
val bitmapRatio = width.toFloat() / height.toFloat()
if (bitmapRatio > 1) {
width = maxSize;
height = (width / bitmapRatio).toInt()
} else {
height = maxSize;
width = (height * bitmapRatio).toInt()
}
result = Bitmap.createScaledBitmap(source, width, height, true)
source.recycle()
}
return result
}
override fun key() = "resize()"
}
Use:
Picasso.get()
.load(url)
.transform(ResizeTransformation(2400)) //FHD+ resolution
.into(view)
Convert your all png formats into webs format. You can do it by Android Studio.

Cannot read image file in appcelerator titanium

I have an image stored at /assets in my project folder and I am trying to read it using Ti.Filesystem.getFile(). The code prints the blob data in android but it prints undefined in iOS.
Following function is called on Button click event https://pastebin.com/QgqLQPyz
function readImg(e) {
var localPath = '/butterfly.jpg';
var cachedFilename = Ti.Utils.sha1(localPath) + localPath.substr(localPath.lastIndexOf('.'));
console.log("cachedFilename:---"+cachedFilename);
var cachedFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, cachedFilename);
if(!cachedFile.exists()){
var blob = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, localPath).read();
console.log("-----------blob in not exists:"+JSON.stringify(blob));
}
}
When the same image path is set in ImageView it gets displayed so the issue is not with path . What am I missing here ? pls help. Thank you.
The best option so you don't have to do anything specific to the images at all (keep in mind, image manipulation is pretty heavy to do on runtime), is to use a module that was made for this purpose, av.imageview. This allows you to configure all kinds of content modes.
An option to get your code to work is to get the blob using the the getAsset method.
var blob = Ti.Filesystem.getAsset('/images/butterfly.jpg');
and then resize where you see fit. But I would advise you, if you do need to do this every time the app runs, then just resize once and store that resized image to be used after that. That way there will only be a single time the image needs resizing.

Images are Getting cached in UWP application

In my UWP application I am binding the images from azure. It is getting cached when it get the response. When I change the image in the azure it's not reflecting in my UI, Instead it display the image from cache.
Is there any way to clear the cache of my UWP application or to restrict the application to cache images?.
Have you tried CreateOptions="IgnoreImageCache"?
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Url}"
CreateOptions="IgnoreImageCache"
DecodePixelWidth="120"
DecodePixelHeight="120" />
</Image.Source>
</Image>
But make sure you set the proper decode pixel width/height to avoid using unnecessary memory.
According to the documentation -
You should only use BitmapCreateOptions.IgnoreImageCache in cases
where you know that the source image file as retrieved by Uniform
Resource Identifier (URI) has the potential to change over time.
Otherwise, setting CreateOptions to use
BitmapCreateOptions.IgnoreImageCache causes all newly retrieved image
sources to be decoded again, which can negatively impact performance.
So maybe try setting None as the default value for CreateOptions, and only update it to IgnoreImageCache once you are absolutely sure that the image has been updated by the cloud. Note CreateOptions is also a dependency property, so you should be able to use data binding too.

How to save Image Control to local file in Windows 8?

I'm writing Client-Server application, in which I get item with Image Url. This Url is binded with Image control:
<Image Source{Binding ImageUrl} x:Name="img_avatar" Stretch="UniformToFill" Width="48" Height="48"/>
I want to save the image from Image.Source to the local folder without any methods which are using download operations.
Please help m someone !!!
There is no way to do what you ask about. When you set an Image control's source to a Uri - it gets converted to a BitmapImage which doesn't expose any API that would let you save the file or even extract a bitmap. If you want to avoid multiple downloads of the image you can download it as a file once and load a BitmapImage from the file instead of Uri.
I believe with a little bit of reflection hackery, it should be doable. But a lot better solutions exist, so yeah..
Either subclass Image or write attached property to handle logic. All you have to do, is just load image yourself into MemoryStream and create BitmapImage manually(behind subclassed Image or attached proeprty).
This way you can expose new property that gives direct access to MemoryStream, and from there you can save file to HDD without wasting precious memory.
Bonus points if you can also keep the Source="{Binding}" syntax while providing this functionality.

Converting Silverlight 4 InkPresenter omits uploaded images when converted to WriteableBitmap

I have a web application that incorporates a Silverlight drawing pad. The strokes are saved as XAML in a database. Additionally, any text or moveableimage objects are also saved in the XAML. The moveableimage objects have as their source images being served from the same server and same domain as the Silverlight application.
In order to perform a scale up on the sketch pad contents, I use a WriteableBitmap:
ScaleTransform transform = new ScaleTransform();
transform.ScaleX = (double)10;
transform.ScaleY = (double)10;
WriteableBitmap fullSizeBinary = new WriteableBitmap(workCanvas, transform);
string fullSizeBinaryString = XamlHelper.GetBase64Jpg(fullSizeBinary);
XamlHelper is a custom class using ImageTools to convert the WriteableBitmap to JPEG. I have tried with and without the transform. The WriteableBitmap omits the child moveableimage objects and the resulting JPEG has all the strokes and text objects, but the moveableimage objects do not render. I have tried a variety of things thinking it was security, memory, distinct controller paths, etc. Nothing. Been banging my head against this for hours and I can't figure it out.
When the method containing the above code is invoked by the user clicking a button inside the Silverlight application, it works perfectly. When the method containing the above code is invoked programmatically (i.e., through a parameter passed into the Silverlight application from an MVC controller) it doesn't work.