Skip to content

Displaying images ​

This guide covers how to use UIImage and UIImageView to display images: images bundled in the app, system icons, images from the network, images in local files, and animated images, as well as how images are positioned, tinted, and stretched. The details of each method and property are on the reference pages of these two classes.

  • Displaying an image takes two steps: get the image, then assign it to an image view. An image view does not load images by itself. All four ways of getting an image return null when the image cannot be obtained, without throwing, so check for null after getting it.
  • Put images as ordinary files in the project's assets/, and get them with UIImage.imageNamed('JS/assets/name'). Projects generated by the command-line tool have no way to add images to an Asset Catalog.
  • Set contentMode explicitly on every image view: for photos and covers, use 'scaleAspectFill' plus clipsToBounds = true; for icons, use 'scaleAspectFit'. The default 'scaleToFill' stretches and distorts the image.
  • Give image views their size with constraints (a fixed width and height, or a fixed width plus an aspect ratio), not by relying on the image's size. Network images have no size until they finish downloading; otherwise the view's size changes when the image arrives.
  • Always call prepareForDisplay() before displaying an image downloaded from the network, to move decoding to the background. Animated images too. Small icons do not need it.

A first image ​

Starting from a blank app, display a pink star icon in the center of the screen. The icon comes from SF Symbols: the icon library built into iOS, with thousands of icons fetched by name, so you do not need to prepare image files yourself.

js
application.addEventListener('sceneconnect', (e) => {
  // Create the window and view controller. Every app needs these lines
  const win = new UIWindow(e.scene);
  const page = new UIViewController();
  page.view.backgroundColor = 'systemBackground';
  win.rootViewController = page;
  win.makeKeyAndVisible();

  // 1. Get an image. 'star.fill' is an icon name in SF Symbols
  const star = UIImage.systemImageNamed('star.fill');

  // 2. Create an image view and give it the image
  const iv = new UIImageView();
  iv.image = star;

  // 3. The image is smaller than the view: scale it up, keeping its aspect ratio, until it just fits in the view
  iv.contentMode = 'scaleAspectFit';

  // 4. Tint the icon
  iv.tintColor = 'systemPink';

  // 5. Put it in the view controller: centered, 120 pt wide and tall
  iv.translatesAutoresizingMaskIntoConstraints = false;
  page.view.addSubview(iv);
  NSLayoutConstraint.activateConstraints([
    iv.centerXAnchor.constraintEqualToAnchor(page.view.centerXAnchor),
    iv.centerYAnchor.constraintEqualToAnchor(page.view.centerYAnchor),
    iv.widthAnchor.constraintEqualToConstant(120),
    iv.heightAnchor.constraintEqualToConstant(120),
  ]);
});

Effect: A solid pink five-pointed star appears in the center of the screen, within a 120 × 120 pt area, undistorted.

This code has not been run as a whole in the simulator. Every API it uses has been run in the acceptance tests.

The five steps are: get the image, create the view and assign the image, set how it is positioned, tint it, and put it in the view controller. Each usage below modifies these five steps and reuses page and iv from here. To try a section on its own, write these lines first:

js
const page = new UIViewController();
const iv = new UIImageView();
page.view.addSubview(iv);

Displaying an image bundled in the app ​

Image files go in assets/ at the project root, and are placed into JS/assets/ in the app bundle at build time.

js
const dot = UIImage.imageNamed('JS/assets/dot');
if (dot) {
  iv.image = dot;
  console.log(dot.size.width, dot.size.height, dot.scale);
}

Effect

  • The image view shows the dot image from the project's assets/ directory.
  • The console prints 10 10 3 (on a device with an @3x screen).

The name can omit the extension. imageNamed() does not search subdirectories, so when the image is in JS/assets/, writing just 'dot' does not find it. When the directory has the three files dot.png, dot@2x.png, and dot@3x.png, the system picks one according to the screen. For the full rules, see imageNamed().

Displaying a system icon ​

js
iv.image = UIImage.systemImageNamed('heart.fill');
iv.contentMode = 'scaleAspectFit';

Effect: The image view shows a solid heart icon, in the image view's tintColor. Not verified in the simulator.

All icon names can be looked up in the SF Symbols app provided by Apple. A name that does not exist returns null.

Tinting an icon ​

js
iv.image = UIImage.systemImageNamed('star.fill');
iv.tintColor = '#FF3B30';
console.log(iv.tintColor);

Effect

  • The star is displayed in red. Not verified in the simulator.
  • The console prints #FF3B30. The color string written reads back unchanged.

tintColor affects only template images: all the opaque parts of the image are shown in tintColor. SF Symbols icons are treated as template images in an image view. Your own images display their original colors by default; to tint them with tintColor too, first convert them to template images:

js
const mark = UIImage.imageNamed('JS/assets/dot');
if (mark) {
  iv.image = mark.imageWithRenderingMode('alwaysTemplate');
  iv.tintColor = 'systemGreen';
}

Effect: All the opaque parts of the image are shown in green, and the original colors are not shown. Not verified in the simulator.

For the rules, see Rendering modes and tintColor.

Displaying an image downloaded from the network ​

js
async function showRemoteImage() {
  const res = await fetch('https://picsum.photos/200/200');
  const blob = await res.blob();

  const img = UIImage.imageWithData(blob);
  if (img === null) {
    console.log('What was downloaded is not an image');
    return;
  }

  // Decode in the background, then display
  const ready = await img.prepareForDisplay();
  iv.image = ready ?? img;
  console.log(img.size.width, img.size.height, img.scale);
}

showRemoteImage();

Effect

  • Once the download completes, the image view shows the image.
  • The console prints 200 200 1.

This is the standard way to display network images. The three steps are: download with fetch and get a Blob, turn the Blob into an image with imageWithData(), and decode in the background with prepareForDisplay().

  • Download with res.blob(), not res.arrayBuffer(): imageWithData() accepts only a Blob.
  • When the downloaded content is not an image (for example, the server returned an error page), imageWithData() returns null without throwing. When the network is unreachable, fetch rejects, so handle it with try…catch; see fetch.
  • The result of prepareForDisplay() may be null; in that case fall back to the original image.
  • The image view is empty during the download. You can give it a backgroundColor as a placeholder.
  • An image obtained from imageWithData() has a scale of 1: a 200 × 200 pixel image has a size of 200 × 200 pt and is shown enlarged on an @3x screen. To treat it as an @2x or @3x image, pass { scale }.
  • When the download is an animated image, the code is the same: prepareForDisplay() decodes all the frames, and it plays automatically once assigned to image.

Caching downloaded images ​

The runtime does not provide an image cache. imageWithData() creates a new image object from the bytes every time. When you need caching, there are two approaches:

  • For reuse while the app is running: keep the obtained UIImage objects in a Map, looked up by URL.
  • To still be available at the next launch: write the downloaded content to the cache directory, and read it from the file later; see the next section.

Displaying an image saved in a local file ​

Save the image as a file first, and read it from the file later. For reading and writing files, see File system.

js
async function showCachedImage() {
  const fs = application.fileSystem;
  const path = fs.caches + '/cover.jpg';

  if (!(await fs.exists(path))) {
    const res = await fetch('https://picsum.photos/200/200');
    await fs.writeBytes(path, await res.blob());
  }

  const img = UIImage.imageWithContentsOfFile(path);
  if (img) {
    iv.image = img;
  }
}

showCachedImage();

Effect: On the first run, the image is downloaded, saved to the cache directory, and displayed. On later runs it is read directly from the file and displayed, without downloading again. This example is not verified in the simulator.

The argument of imageWithContentsOfFile() is a full absolute path. When the file does not exist or is not an image, it returns null.

Displaying an animated image ​

Suppose the project's assets/ directory has an anim.gif with 4 frames, 0.1 seconds each, looping forever.

js
const loading = UIImage.imageNamed('JS/assets/anim.gif');
if (loading !== null) {
  iv.image = loading;
  console.log(loading.images === null ? 0 : loading.images.length);
  console.log(loading.duration.toFixed(1), loading.loopCount);
}

Effect

  • The image in the image view starts playing and loops forever.
  • The console prints 4, then 0.4 Infinity: 4 frames, 0.4 seconds per playthrough, looping forever.

When getting an animated image, include the extension in the name: without an extension, imageNamed() looks only for .png files. APNG's extension is .png, so it can be omitted.

For the playback rules, see Animated image playback. Assign small animated images such as emoji and loading indicators directly to an image view; an animated image larger than 64 MB after decoding shows only its first frame; see How much memory animated images use.

Stopping an animated image ​

loading is the animated image read in the previous section; the first line reads it again:

js
const loading = UIImage.imageNamed('JS/assets/anim.gif');
const frames = loading === null ? null : loading.images;
if (frames !== null) {
  iv.image = frames[0];
}

Effect: Playback stops, and the image view shows the first frame.

Each frame in images is a still image and can be displayed on its own. To show the last frame, use frames[frames.length - 1]. Assign loading back to image, and the animated image plays from the beginning.

Controlling animated image playback yourself ​

An animated image in an image view cannot be paused, and there is no notification when it finishes. When you need these, do not use an image view; hand the frames to a layer and play them with a keyframe animation. loading is the animated image read in the Displaying an animated image section; the first line reads it again:

js
const loading = UIImage.imageNamed('JS/assets/anim.gif');
const allFrames = loading === null ? null : loading.images;
const durations = loading === null ? null : loading.frameDurations;
if (loading !== null && allFrames !== null && durations !== null) {
  // 1. A layer whose content is first set to the last frame: that is what shows after the animation finishes
  const layer = new CALayer();
  layer.frame = new CGRect(20, 80, 48, 48);
  layer.contents = allFrames[allFrames.length - 1];
  page.view.layer.addSublayer(layer);

  // 2. The moment each frame starts, as a fraction of the total duration. One more than the number of frames; the last is 1
  const keyTimes = [];
  let elapsed = 0;
  for (const seconds of durations) {
    keyTimes.push(elapsed / loading.duration);
    elapsed += seconds;
  }
  keyTimes.push(1);

  // 3. A keyframe animation: show each frame in turn, with no transition between frames
  const play = CAKeyframeAnimation.animationWithKeyPath('contents');
  play.values = allFrames;
  play.keyTimes = keyTimes;
  play.calculationMode = 'discrete';
  play.duration = loading.duration;
  play.repeatCount = 2;
  play.addEventListener('stop', (event) => {
    console.log('Finished playing', event.finished);
  });
  layer.addAnimation(play, { forKey: 'play' });
}

Effect

  • A 48 × 48 pt layer appears near the top left of the view controller, plays the animated image twice, and then stops on the last frame.
  • When it finishes, the console prints Finished playing true.

This code has not been run as a whole in the simulator. The acceptance tests check that each step in it does not throw and that the animation is attached to the layer, without waiting for it to finish.

  • Replace repeatCount with loading.loopCount, and the number of playthroughs matches what the file specifies. When loopCount is Infinity, it loops forever.
  • To stop partway, use layer.removeAnimationForKey('play'); in that case the stop event's finished is false.
  • A frame-by-frame animation from a separate set of images is written the same way, with that set of images as values.

Positioning when the image and view have different proportions ​

js
iv.contentMode = 'scaleAspectFill';
iv.clipsToBounds = true;

Effect: The image scales up or down, keeping its aspect ratio, until it covers the whole view. The parts beyond the view are not shown. Not verified in the simulator.

For the results of each contentMode, see Will the image be distorted.

Note: contentMode only decides how the image is positioned, not clipping. When using 'scaleAspectFill' without setting clipsToBounds = true, the overflow is shown outside the view, covering neighboring content.

Making the view's height follow the image's proportions ​

If you want neither distortion nor empty space or cropping, make the view's aspect ratio match the image.

js
const photo = UIImage.imageNamed('JS/assets/dot');
if (photo) {
  iv.image = photo;
  const width = 200;
  const height = width * (photo.size.height / photo.size.width);
  iv.frame = new CGRect(20, 100, width, height);
}

Effect: The image view is 200 pt wide, and its height is computed from the image's aspect ratio. The image fills the view exactly, undistorted. Not verified in the simulator.

Sizing an image view with constraints ​

This is the recommended way to use an image view with constraints: the position and width are set by constraints, the height follows the width at a fixed aspect ratio, and contentMode handles the case where the image's and view's proportions differ.

js
const cover = new UIImageView();
cover.contentMode = 'scaleAspectFill';
cover.clipsToBounds = true;
cover.backgroundColor = 'secondarySystemBackground';   // placeholder background until the image arrives
cover.translatesAutoresizingMaskIntoConstraints = false;
page.view.addSubview(cover);

const safe = page.view.safeAreaLayoutGuide;
NSLayoutConstraint.activateConstraints([
  cover.topAnchor.constraintEqualToAnchor(safe.topAnchor, { constant: 16 }),
  cover.leadingAnchor.constraintEqualToAnchor(safe.leadingAnchor, { constant: 16 }),
  cover.trailingAnchor.constraintEqualToAnchor(safe.trailingAnchor, { constant: -16 }),
  // height = width × 9/16
  cover.heightAnchor.constraintEqualToAnchor(cover.widthAnchor, { multiplier: 9 / 16 }),
]);

Effect: A gray area with a 16:9 aspect ratio appears at the top of the view controller, 16 pt from the screen edge on each side. Afterward, assigning an image of any proportion to cover.image makes it fill this area without distortion; the overflow is not shown, and the view's size does not change. This code is not verified in the simulator.

Once both width and height are fixed by constraints, the image's size no longer affects the view's size. Other content in the view controller keeps its position before and after a network image arrives.

When only the position is constrained and not the width and height, the view's size equals the image's size. This approach suits small icons of known size.

Making a stretchable background image (nine-slice) ​

Background images such as speech bubbles and rounded borders need to stretch to any size without distorting their four corners. The approach is to specify how wide a band along each of the four edges is excluded from stretching, and stretch only the middle part. This technique is called nine-slice.

js
const frameImage = UIImage.imageNamed('JS/assets/frame');   // a 20 × 20 pt rounded border
if (frameImage) {
  iv.image = frameImage.resizableImage({
    withCapInsets: new UIEdgeInsets(6, 6, 6, 6),
    resizingMode: 'stretch',
  });
  iv.frame = new CGRect(20, 100, 280, 80);
}

Effect: The border image fills the 280 × 80 pt view. The four corners keep their original size and shape, the four edges stretch only along their own direction, and the middle 8 × 8 pt stretches to fill the remaining area. Not verified in the simulator.

The four numbers of withCapInsets are the widths kept on the top, left, bottom, and right edges, in pt.

Note: Without resizingMode, the middle part is tiled ('tile'), not stretched. When the middle is a solid color the two look the same; with a gradient or pattern they differ.

Switching to another image when pressed ​

An image view can hold two images: it normally shows image, and shows highlightedImage when isHighlighted is true.

js
iv.image = UIImage.systemImageNamed('star');
iv.highlightedImage = UIImage.systemImageNamed('star.fill');

iv.isHighlighted = true;

Effect: After isHighlighted is set to true, the image view switches from an outlined star to a solid star. Setting it back to false switches back to the outlined star. The image switch is not verified in the simulator.

The system does not change isHighlighted automatically. When you need "switch images automatically while a finger is held down", use UIButton's setImage() to set a separate image for the highlighted state.

Clearing the image ​

js
iv.image = null;

Effect: The image view no longer shows an image, leaving only the background color (if backgroundColor was set). Not verified in the simulator.

Generating a thumbnail ​

When the display size is much smaller than the original image (for example, avatars in a list), get a scaled-down image to display.

js
async function showThumbnail() {
  const big = UIImage.imageNamed('JS/assets/dot');
  if (big === null) return;

  const thumbnail = await big.prepareThumbnail(new CGSize(5, 5));
  if (thumbnail) {
    iv.image = thumbnail;
  }
}

showThumbnail();

Effect: The image view shows a scaled-down image. The thumbnail is generated in the background. The actual size of the thumbnail is not verified in the simulator.

Switching to a different image in Dark Mode ​

In projects generated by the command-line tool, "switch images automatically in Dark Mode" is not possible. Instead, listen for the traitchange event and switch the image in the callback; see Supporting Dark Mode.

See also ​