Monday, April 9, 2018

AssetImage and ExactAssetImage in Flutter and Dart for resolution aware images



AssetImage class for resolution aware pictures. And ExactAssetImage will load a image from resources in your app according to asset name and scale. To use this class we can use Image widget. Note: in the previous video I have explain Image.asset() name constructor. That constructor for static images.

First of all create a directory called assets(any name you want) in your project's root directory. Inside that directory create another two directories for higher resolution images. Those directories should name according to spec. For images with 1.0 or less than that will use the main asset. and for the two times higher image name the directory as 2.0x and for the three times higher resolution, create another directory called 3.0x.

As a example:

assets/egocoding.png
assets/2.0x/egocoding.png
assets/3.0x/egocoding.png

Note: image name should be same for those three images. As you can see in above example.

To use these images in our app we have to specify main asset in pubspec.yaml file's flutter section(as below):

name: image_app
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:

  # To add assets to your application, add an assets section,
  #like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg
  assets:
    - assets/egocoding.png

Code for main.dart:

import 'package:flutter/material.dart';

void main() => runApp(new AssetExample());

class AssetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Assets',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Assets'),
        ),
        body: new Image(
          image: new AssetImage('assets/egocoding.png'),
          width: 300.0,
          height: 300.0,
        ),
      ),
    );
  }
}

For ExactAssetImage change image property to below line:

image: new ExactAssetImage('assets/egocoding.png', scale: 2.0,)

If you did not specify width and height you want get expected result.

Read more: https://flutter.io/assets-and-images/

Images used in this example:

My main image is: 100 x 100


2.0x image should be 100*2 x 100*2


3.0x image should be 100*3 x 100*3



No comments:

Post a Comment