Windows phone image resource

Содержание
  1. Ресурсы и стили
  2. Концепция ресурсов в Windows Phone 8.1
  3. Image. Source Property
  4. Definition
  5. Property Value
  6. Remarks
  7. Setting Source in XAML
  8. Setting Source in code
  9. Using a relative URI in code
  10. Using files from a network
  11. Using files from local storage
  12. Using a stream source to show images from the Pictures library
  13. Image sources and scaling
  14. Image sources and resource qualifiers
  15. Загрузка изображений и ресурсов, адаптированных по масштабированию, теме, высокой контрастности и другим аспектам Load images and assets tailored for scale, theme, high contrast, and others
  16. Квалификация ресурса изображения по масштабу, теме и контрастности Qualify an image resource for scale, theme, and contrast
  17. Ссылки на изображения и другие ресурсы из кода и разметки XAML Reference an image or other asset from XAML markup and code
  18. Квалификация ресурса изображения по targetsize Qualify an image resource for targetsize
  19. Ссылка на файл изображения из манифеста пакета приложения Refer to an image file from your app package manifest
  20. Квалификация ресурса изображения по layoutdirection Qualify an image resource for layoutdirection
  21. Загрузка изображения для конкретного языка или другого контекста Load an image for a specific language or other context
  22. Обновление изображений в качестве реакции на события изменения значений квалификаторов Updating images in response to qualifier value change events

Ресурсы и стили

Концепция ресурсов в Windows Phone 8.1

Ресурсы позволяют определить объекты, которые могут многократно использоваться в приложении в различных его частях. Итак, определим пару ресурсов и используем их:

Получится такая кнопка:

Ресурсы определяются в свойстве Resources , которое есть у компонентов визуального интерфейса. В данном случае ресурсы определены как ресурсы элемента Page внутри тегов

Каждый ресурс должен иметь уникальный идентификатор, которым выступает свойство x:Key .

Чтобы задать ресурс в качестве значения свойство, используется выражение

В качестве ресурсов можно определить и более сложное содержимое, например:

Если у нас в проекте несколько страниц Page, и нам надо использовать одинаковые ресурсы на каждой из них, то мы можем определить данные ресурсы в качестве ресурсов всего приложении. Для этого откроем файл App.xaml и добавим в него определение ресурсов:

В этом случае данные ресурсы будут доступны из любого места приложения.

Кроме подключения ресурсов через StaticResource в разметке по умолчанию можно увидеть в определении Page такое выражение Background=»» . ThemeResource позволяет подключить ранее созданную тему для приложения. Подобных тем существует довольно много для разных типов элементов:

Image. Source Property

Definition

Gets or sets the source for the image.

Property Value

An object that represents the image source file for the drawn image. Typically you set this with a BitmapImage object, constructed with the Uniform Resource Identifier (URI) that describes the path to a valid image source file. Or, you can initialize a BitmapSource with a stream, perhaps a stream from a storage file.

Remarks

Setting the Source property is inherently an asynchronous action. Because it’s a property, there isn’t an awaitable syntax, but for most scenarios you don’t need to interact with the asynchronous aspects of image source file loading. The framework will wait for the image source to be returned, and will rerun layout when the image source file becomes available.

Setting the source to a Uniform Resource Identifier (URI) value that can’t be resolved to a valid image source file does not throw an exception. Instead, it fires an ImageFailed event. Decoding failures also fire ImageFailed. You can write an ImageFailed handler and attach it to the Image object to detect this, and possibly use the ErrorMessage in event data to determine the nature of the failure. Also, if you want to verify that an image source file was loaded correctly, you can handle the ImageOpened event on the Image element.

Setting Source in XAML

You can set the Source property as an attribute in XAML. In this case, you’re setting the Source attribute value as a Uniform Resource Identifier (URI) string that describes the location of the source image file. This behavior relies on underlying type conversion that processes the string as a Uniform Resource Identifier (URI), and calls the equivalent of the BitmapImage(Uri) constructor. Setting the Source property using a Uniform Resource Identifier (URI) string is a shortcut enabled by XAML. Note that the Uniform Resource Identifier (URI) here appears to be a relative Uniform Resource Identifier (URI); supporting partial Uniform Resource Identifier (URI) is another XAML shortcut.

The XAML parser interprets any strings that represent a relative Uniform Resource Identifier (URI) using the base Uniform Resource Identifier (URI) of the XAML page that is being parsed. For example, if you specify a value «Images/myImage.png» in XAML, that string is interpreted as a relative path suffix that is appended to the base Uniform Resource Identifier (URI) location within the app package where the XAML page itself exists. If the previous Image element is added to a page that’s in the root of the app package, the Uniform Resource Identifier (URI) is interpreted as ms-appx:///Images/myImage.png. If the Image is added to a page that’s in a Pages folder in the app, the Uniform Resource Identifier (URI) is interpreted as ms-appx:///Pages/Images/myImage.png.

If the source image is not part of the app package, you must use an absolute Uniform Resource Identifier (URI) to set the Source property in XAML. For more info, see How to load file resources, and examples later in this document.

A property element syntax in XAML is also possible, specifying a BitmapImage object element with valid source as the property value.

Setting Source in code

To set the Image.Source property in code requires an instance of BitmapImage (or BitmapSource ), which you also must construct. If your image source is a stream, use the async SetSourceAsync method of BitmapImage to define the image information from the stream.

If your image source is a file referenced by Uniform Resource Identifier (URI), set the BitmapImage.UriSource property, or use the BitmapImage constructor that takes a Uniform Resource Identifier (URI) parameter. The Windows Runtime enforces that a Uniform Resource Identifier (URI) must be absolute; you can’t use relative Uniform Resource Identifier (URI) in Windows Runtime code. If you are using a .NET Framework System.Uri value, and you use a signature that requires a UriKind value, make sure to specify Absolute.

When you reference local content, you must include the ms-appx: scheme in the absolute Uniform Resource Identifier (URI) that you use as the BitmapImage.UriSource. In code, you don’t get the processing shortcuts for combining relative Uniform Resource Identifier (URI) parts and the ms-appx: scheme that happens automatically if you specify Source as a XAML attribute. Instead you must explicitly construct an absolute Uniform Resource Identifier (URI) with the appropriate scheme.

Here’s how to set the source to an image from the app package.

If you need to ensure that the Image control is ready before trying to use it in code, handle the Loaded event, and set the Source property in the event handler.

Читайте также:  Как установить windows с харда

The FrameworkElement.Loaded event occurs when the Image control is loaded into the XAML page. The ImageOpened event occurs when the image file is opened in the Image control.

Here’s an example of setting Image.Source in the handler for the Loaded event. In this example, the Image object was created in XAML but doesn’t have a source or any other property values; instead these values are provided at run-time when the Image is loaded from XAML.

You can handle the ImageOpened event if there are any timing issues with retrieving or decoding the image source, where you might need alternate content to display until the image source is available. See XAML images sample for example code.

Using a relative URI in code

We saw previously that the XAML parser interprets a relative Uniform Resource Identifier (URI) using the base Uniform Resource Identifier (URI) of the XAML page that is being parsed. To achieve the same result in code, you can construct a Uri using one of the constructors that creates a Uniform Resource Identifier (URI) by combining an absolute base and then a relative path within that location. For the first parameter, call BaseUri on Page where the Image is loaded. (You can also call BaseUri on the Image instance where you are setting the source, or another element on the page. See the Caution below.) This creates a Uniform Resource Identifier (URI) with the ms-appx: scheme and adds the path that is part of the XAML page’s location. For the second parameter, pass the relative Uniform Resource Identifier (URI) string that describes the source image location.

In C# or Microsoft Visual Basic, the Uri type is projected as System.Uri, so use the System.Uri(Uri, String) constructor that takes a string as the second parameter. In VisualВ C++ component extensions (C++/CX) use Uri(String,String).

If you instantiate a new Image in code, the BaseUri property is null until the Image is added to the visual tree of the a page. For example, the following code throws an ArgumentNull exception. To avoid the exception, add the Image to the visual tree before setting the Source property.

This example throws an exception because it calls BaseUri on the Image before the Image is added to the page. It’s assumed that ‘stackPanel1’ is a StackPanel element declared in XAML.

To avoid this error, you can call BaseUri on the Page itself, as shown previously, or add the Image to the page before calling BaseUri, as shown here.

In this example, the Image is added to the page before the call to BaseUri, so BaseUri is not null. It’s assumed that ‘stackPanel1’ is a StackPanel element declared in XAML.

Using files from a network

To use a file from a network location as an image source, use the http: or https: schemes, as shown here. Specify the absolute Uniform Resource Identifier (URI). For more info, see How to load file resources.

Using files from local storage

To use files that are placed in your app’s local storage as an image source , use the ms-appdata: scheme, as shown here. Specify the absolute Uniform Resource Identifier (URI). For more info, see How to load file resources.

GetFileFromApplicationUriAsync(uri); auto img = ref new Image(); img->Source = file;]]> —>

Using a stream source to show images from the Pictures library

A typical use of Image elements in an app is to show pictures from the user’s Pictures library. These pictures might be accessed programmatically or through a FileOpenPicker. In either case, the StorageFile object you get can be opened as a stream, but doesn’t provide a Uniform Resource Identifier (URI) reference to the image file. To use a stream as an image source, you must write code that sets your Image instance to use the stream. This can’t be done in XAML alone.

To display an individual image, use the StorageFile objects from enumerating the library and call OpenAsync to obtain a stream. Use this stream to set the image source, by creating a new BitmapImage, then calling SetSourceAsync and passing the stream to use as the streamSource parameter.

This example shows how to use a FileOpenPicker to access an image file from the Pictures library and set it as the Source of an Image control. The code is already awaitable because it’s waiting for the user to choose a file and it only runs after that happens. The stream to use comes from StorageFile.OpenAsync after a StorageFile instance is returned from the async picker actions. For more info on using file pickers, see Open files and folders with a picker.

This example shows how to programmatically access an image file from the Pictures library and set it as the Source of an Image control. To access the content of the Pictures library programmatically, call StorageFolder.GetFilesAsync. Remember that you need to specify a capability to access the Pictures library programmatically.

Image sources and scaling

If you are referencing images that are packaged in your app, you should create your image sources at several recommended sizes, to ensure that your app looks great when the Windows Runtime scales it. When specifying a Source for an Image as a Uniform Resource Identifier (URI), you can use a naming convention that will automatically reference the correct image resource for the current scaling as detected by the system at run-time. For specifics of the naming convention and more info, see Quickstart: Using file or image resources.

For more info on how to design for scaling, see Screen sizes and breakpoints or Remarks in Image.

Image sources and resource qualifiers

You can use automatic handling for accessing unqualified resources with current scale and culture qualifiers, or you can use ResourceManager and ResourceMap with qualifiers for culture and scale to obtain the resources directly. For more info see Resource management system or Remarks in Image. For more info on app resources and how to package image sources in an app, see Defining app resources.

Загрузка изображений и ресурсов, адаптированных по масштабированию, теме, высокой контрастности и другим аспектам Load images and assets tailored for scale, theme, high contrast, and others

Приложение может загружать файлы ресурсов изображений (или другие файлы ресурсов), адаптированные по контексту коэффициента масштабирования дисплея, темы, высокой контрастности и другим аспектам. Your app can load image resource files (or other asset files) tailored for display scale factor, theme, high contrast, and other runtime contexts. На эти изображения можно ссылаться из императивного кода или разметки XAML, например в виде свойства Source объекта Image. These images can be referenced from imperative code or from XAML markup, for example as the Source property of an Image. Они также могут появляться в исходном файле манифеста пакета приложения (файле Package.appxmanifest ) — например, в качестве значения для App Icon на вкладке Visual Assets в конструкторе манифеста Visual Studio — или на плитке и всплывающих уведомлениях. They can also appear in your app package manifest source file (the Package.appxmanifest file)—for example, as the value for App Icon on the Visual Assets tab of the Visual Studio Manifest Designer—or on your tiles and toasts. Используя квалификаторы в именах файлов изображений при необходимости динамической их загрузке с помощью ResourceContext, можно обеспечить загрузку наиболее подходящего файла изображения, который наилучшим образом соответствует параметрам среды выполнения пользователя для масштабирования дисплея, темы, высокой контрастности, языку и другим аспектам. By using qualifiers in your images’ file names, and optionally dynamically loading them with the help of a ResourceContext, you can cause the most appropriate image file to be loaded that best matches the user’s runtime settings for display scale, theme, high contrast, language, and other contexts.

Читайте также:  Добавить переменную окружения линукс

Ресурс изображения содержится в файле ресурсов изображений. An image resource is contained in an image resource file. Также можно представить себе изображение в качестве ресурса, а содержащий его файл — в качестве файла ресурса; и эти файлы ресурсов находятся в папке \Assets вашего проекта. You can also think of the image as an asset, and the file that contains it as an asset file; and you can find these kinds of resource files in your project’s \Assets folder. Общие сведения об использовании квалификаторов в именах файлов ресурсов изображений приводятся в разделе Адаптация ресурсов для языка, масштаба и других квалификаторов. For background on how to use qualifiers in the names of your image resource files, see Tailor your resources for language, scale, and other qualifiers.

Вот некоторые распространенные квалификаторы изображений: scale, theme, contrast и targetsize. Some common qualifiers for images are scale, theme, contrast, and targetsize.

Квалификация ресурса изображения по масштабу, теме и контрастности Qualify an image resource for scale, theme, and contrast

По умолчанию для квалификатора scale используется значение scale-100 . The default value for the scale qualifier is scale-100 . Таким образом, эти два варианта эквивалентны (они предоставляют изображение в масштабе 100, то есть с коэффициентом масштабирования 1). So, these two variants are equivalent (they both provide an image at scale 100, or scale factor 1).

Можно использовать квалификаторы в именах папок вместо имен файлов. You can use qualifiers in folder names instead of file names. Это более подходящий метод, если у вас есть несколько файлов ресурсов для каждого квалификатора. That would be a better strategy if you have several asset files per qualifier. Для наглядности ниже приведены еще два варианта, эквивалентные приведенным выше. For purposes of illustration, these two variants are equivalent to the two above.

Далее приведен пример того, как можно предоставлять варианты ресурсов изображений — с именем /Assets/Images/logo.png — для различных параметров масштабирования дисплея, темы и высокой контрастности. Next is an example of how you can provide variants of an image resource—named /Assets/Images/logo.png —for different settings of display scale, theme, and high contrast. В этом примере используется именование папки. This example uses folder naming.

Ссылки на изображения и другие ресурсы из кода и разметки XAML Reference an image or other asset from XAML markup and code

Именем — или идентификатором — ресурса изображения является его путь и имя файла без каких-либо квалификаторов. The name—or identifier—of an image resource is its path and file name with any and all qualifiers removed. Если вы назовете папки или файлы как в любом из примеров в предыдущем разделе, у вас будет один ресурс изображений, а его имя (как абсолютный путь) будет /Assets/Images/logo.png . If you name folders and/or files as in any of the examples in the previous section, then you have a single image resource and its name (as an absolute path) is /Assets/Images/logo.png . Вот как использовать это имя в разметке XAML. Here’s how you use that name in XAML markup.

Обратите внимание, что вы используете схему URI ms-appx , так как ссылаетесь на файл, который поступает из пакета приложения. Notice that you use the ms-appx URI scheme because you’re referring to a file that comes from your app’s package. См. раздел Схемы URI. See URI schemes. А вот как добавить ссылку на тот же ресурс изображения в императивный код. And here’s how you refer to the same image resource in imperative code.

Можно использовать ms-appx для загрузки любого произвольного файла из пакета приложения. You can use ms-appx to load any arbitrary file from your app package.

Схема ms-appx-web обращается к тем же файлам, что и ms-appx , но в разделе web. The ms-appx-web scheme accesses the same files as ms-appx , but in the web compartment.

Для любых сценариев, показанных в этих примерах, используйте перегрузку конструктора Uri, которая выводит UriKind. For any of the scenarios shown in these examples, use the Uri constructor overload that infers the UriKind. Укажите допустимый абсолютный URI, включая схему и полномочия, или просто оставьте для полномочий значение по умолчанию для пакета приложения, как показано в примере выше. Specify a valid absolute URI including the scheme and authority, or just let the authority default to the app’s package as in the example above.

Обратите внимание, как в кодах URI в этом примере за схемой ( ms-appx или ms-appx-web ) следует :// , а далее указан абсолютный путь. Notice how in these example URIs the scheme (» ms-appx » or » ms-appx-web «) is followed by » :// » which is followed by an absolute path. В абсолютном пути начальный символ / обеспечивает его интерпретацию из корневого каталога пакета. In an absolute path, the leading » / » causes the path to be interpreted from the root of the package.

ms-resource Схемы URI (для строковых ресурсов) и ms-appx(-web) (для изображений и других активов) выполняют автоматическое сопоставление квалификаторов для поиска ресурса, наиболее подходящего для текущего контекста. The ms-resource (for string resources) and ms-appx(-web) (for images and other assets) URI schemes perform automatic qualifier matching to find the resource that’s most appropriate for the current context. Схема URI ms-appdata (которая используется для загрузки данных приложения) не выполняет никакое автоматическое сопоставление, но вы можете реагировать на содержимое ResourceContext.QualifierValues и явно загружать соответствующие ресурсы из данных приложения, используя полное имя физического файла в URI. The ms-appdata URI scheme (which is used to load app data) does not perform any such automatic matching, but you can respond to the contents of ResourceContext.QualifierValues and explicitly load the appropriate assets from app data using their full physical file name in the URI. Подробнее о данных приложения: Хранение и извлечение параметров и прочих данных приложения. For info about app data, see Store and retrieve settings and other app data. Веб-схемы URI (например, http , https и ftp ) также не выполняют автоматическое сопоставление. Web URI schemes (for example, http , https , and ftp ) do not perform automatic matching, either. Сведения о том, что делать в этом случае, см. в разделе Размещение и загрузка изображений в облаке. For info about what to do in that case, see Hosting and loading images in the cloud.

Читайте также:  0x00000109 windows server 2019

Абсолютные пути удобны, если файлы изображений остаются там, где они находятся в структуре проекта. Absolute paths are a good choice if your image files remain where they are in the project structure. Если вы хотите иметь возможность перемещать файл изображения, но следите за тем, чтобы он оставался в том же расположении относительно ссылающегося на него файла разметки XAML, то вместо абсолютного пути вам может потребоваться использовать путь, который задается относительно файла, содержащего разметку. If you want to be able to move an image file, but you’re careful that it remains in the same location relative to its referencing XAML markup file, then instead of an absolute path you might want to use a path that’s relative to the containing markup file. Если применяется такой способ, использовать схему URI не требуется. If you do that, then you needn’t use a URI scheme. В этом случае вы по-прежнему сможете использовать преимущества автоматического сопоставления квалификаторов, но только потому, что используете относительный путь в разметке XAML. You will still benefit from automatic qualifier matching in this case, but only because you are using the relative path in XAML markup.

Квалификация ресурса изображения по targetsize Qualify an image resource for targetsize

Можно использовать квалификаторы scale и targetsize для различных вариантов одного ресурса изображения, но нельзя использовать оба этих квалификатора для одного варианта ресурса. You can use the scale and targetsize qualifiers on different variants of the same image resource; but you can’t use them both on a single variant of a resource. Также необходимо задать хотя бы один вариант без квалификатора TargetSize . Also, you need to define at least one variant without a TargetSize qualifier. Этот вариант должен либо определять значение для scale , либо разрешать использовать по умолчанию scale-100 . That variant must either define a value for scale , or let it default to scale-100 . Таким образом, эти два варианта ресурса /Assets/Square44x44Logo.png являются допустимыми. So, these two variants of the /Assets/Square44x44Logo.png resource are valid.

И эти два варианта допустимы. And these two variants are valid.

Но этот вариант недопустим. But this variant is not valid.

Ссылка на файл изображения из манифеста пакета приложения Refer to an image file from your app package manifest

Если вы назовете папки или файлы как в любом из двух допустимых примеров в предыдущем разделе, у вас будет один ресурс изображения со значком приложения, а его имя (как относительный путь) будет Assets\Square44x44Logo.png . If you name folders and/or files as in either of the two valid examples in the previous section, then you have a single app icon image resource and its name (as a relative path) is Assets\Square44x44Logo.png . В манифесте пакета приложения просто приведите ссылку на ресурс по имени. In your app package manifest, simply refer to the resource by name. Нет необходимости использовать какую-либо схему URI. There’s no need to use any URI scheme.

Это все, что необходимо сделать, и операционная система будет выполнять автоматическое сопоставление квалификаторов для поиска ресурса, который больше всего подходит текущему контексту. That’s all you need to do, and the OS will perform automatic qualifier matching to find the resource that’s most appropriate for the current context. Список всех элементов в манифесте пакета приложения, которые можно локализовать или иначе квалифицировать таким образом, см. в разделе Локализуемые элементы манифеста. For a list of all items in the app package manifest that you can localize or otherwise qualify in this way, see Localizable manifest items.

Квалификация ресурса изображения по layoutdirection Qualify an image resource for layoutdirection

Загрузка изображения для конкретного языка или другого контекста Load an image for a specific language or other context

Дополнительные сведения о преимуществах локализации приложений см. в разделе Глобализация и локализация. For more info about the value proposition of localizing your app, see Globalization and localization.

По умолчанию ResourceContext (полученный из ResourceContext.GetForCurrentView) содержит значение квалификатора для каждого имени квалификатора, представляя контекст среды выполнения по умолчанию (другими словами, параметры для текущего пользователя и компьютера). The default ResourceContext (obtained from ResourceContext.GetForCurrentView) contains a qualifier value for each qualifier name, representing the default runtime context (in other words, the settings for the current user and machine). Файлы изображений сопоставляются — на основании квалификаторов в именах — со значениями квалификаторов в этом контексте среды выполнения. Image files are matched—based on the qualifiers in their names—against the qualifier values in that runtime context.

Но в некоторых ситуациях вашему приложению требуется переопределить параметры системы и явно задать использование языка, масштаба или другого значения квалификатора при поиске подходящего изображения для загрузки. But there might be times when you want your app to override the system settings and be explicit about the language, scale, or other qualifier value to use when looking for a matching image to load. Например, может потребоваться точное управление загрузкой определенных высококонтрастных изображений. For example, you might want to control exactly when and which high contrast images are loaded.

Это можно сделать, создав новый ResourceContext (вместо используемого по умолчанию) и переопределив его значения, а затем использовать этот объект контекста при поиске изображения. You can do that by constructing a new ResourceContext (instead of using the default one), overriding its values, and then using that context object in your image lookups.

Для обеспечения того же эффекта на глобальном уровне можно переопределить значения квалификатора в ResourceContext по умолчанию. For the same effect at a global level, you can override the qualifier values in the default ResourceContext. Но вместо этого рекомендуется вызвать ResourceContext.SetGlobalQualifierValue. But instead we advise you to call ResourceContext.SetGlobalQualifierValue. Следует задать значения один раз с помощью вызова SetGlobalQualifierValue и затем эти значения всегда используются в ResourceContext по умолчанию для поиска. You set values one time with a call to SetGlobalQualifierValue and then those values are in effect on the default ResourceContext each time you use it for lookups. По умолчанию класс ResourceManager использует ResourceContext по умолчанию. By default, the ResourceManager class uses the default ResourceContext.

Обновление изображений в качестве реакции на события изменения значений квалификаторов Updating images in response to qualifier value change events

Запущенное приложение может реагировать на изменения в параметрах системы, которые влияют на значения квалификаторов в контексте ресурсов по умолчанию. Your running app can respond to changes in system settings that affect the qualifier values in the default resource context. Любой из этих параметров системы вызывает событие MapChanged на ResourceContext.QualifierValues. Any of these system settings invokes the MapChanged event on ResourceContext.QualifierValues.

В ответ на это событие можно снова загрузить изображения с помощью ResourceContext по умолчанию, который ResourceManager использует по умолчанию. In response to this event, you can reload your images with the help of the default ResourceContext, which ResourceManager uses by default.

Оцените статью