Create an image in NativeScript from file using code

For my NS Angular projects, I often have images inside the src/images directory that I want to display in my app – for example on a Map. The docs on how to create an Image object and load its source from code (TypeScript) are pretty fuzzy. However, it is pretty straightforward (shared/utils/image.ts):

import { Image } from 'tns-core-modules/ui/image';
import { path, knownFolders } from 'tns-core-modules/file-system';
import { fromFile } from 'tns-core-modules/image-source';

export function imageFromLocal(fileNameInImagesFolder: string): Image {
    const img = new Image();
    const folder = knownFolders.currentApp();
    const folderPath: string = path.join(
        folder.path,
        `images/${fileNameInImagesFolder}`
    );
    img.imageSource = fromFile(folderPath);
    return img;
}

Using it is then super easy (map.service.ts):

...
        this.curLocationMarker = new Marker();
        this.curLocationMarker.icon = imageFromLocal(
            'btn_google_dark_normal_ios@3x.png'
        );
...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close