In this article, we will look at the different ways to show images in a NativeScript application. Images are added to an application either declaratively (XML) or with code (JS).
<Image src="~/logo.png" />
var image = new imageModule.Image(); image.src = "~/logo.png"; dockLayout.addChild(image);
The prefix of the
src value specifies where the image will be loaded form. The possible options are:
- From URL (
- From local file system (
- From resource (
You can also use the image-source module to create an image source and manually set it to the image:
var image = new imageModule.Image(); var imageSource = imageSourceModule.fromResource("logo"); image.imageSource = imageSource;
You can also use the image-source API to save and load images from a base64 encoded string.
Web images have an
https:// prefix. When such an image is loaded, an asynchronous http request will be sent and the image will be shown if the request is successful.
<Image src="https://www.google.com/images/errors/logo_sm_2.png" />
You can manually create an ImageSource instance from URL.
~/ prefix, you can load images relative to the
App folder inside your project.
<Image src="~/images/logo.png" stretch="none" />
You can manually create an ImageSource instance from local file.
res:// prefix you can load a resource image. This is the suggested approach, as it uses the native methods for loading the best image for the current device screen density.
<Image src="res://logo" stretch="none" />
You can manually create an ImageSource instance from resource.
The file extension is not included when referencing resource images.
The actual resource images should be added to the
App_Resources folder in your application and should follow the platform guidelines.
Android resources should be added to the corresponding
drawable-XXX folders inside the
App_Resources\Android folder in your app:
The content of this directory will be copied inside the
platforms\android\res when the app is prepared by the NativeScript CLI. More information about how to use drawable resources in Android can be found here.
IOS resources should be added inside the
App_Resources\ios folder in your app. You can use
@3x suffixes to target devices with a specific screen scale. Here is a list of devices for each scale factor:
- @1x - iPad 2 and iPad mini (1st Generation)
- @2x - iPhone 4s, iPhone 5, iPhone 6, iPad (retina)
- @3x - iPhone 6 Plus
For more information, see Icon and Image Sizes in the iOS Developer Library.
Once the NativeScript project is prepared (
tns prepare ios) all the images will be copied to the
iOS images must be