- Change the font size of all controls in the application (win forms)
- 2 Answers 2
- Как изменить шрифт и его цвет в Label
- Адресная книга
- Шрифты в Xamarin.Forms Fonts in Xamarin.Forms
- Задание атрибутов шрифта Set font attributes
- Задать размер шрифта Set the font size
- Задание семейства шрифтов Set the font family
- Установка свойств шрифта для каждой платформы Set font properties per platform
- Общие сведения об именованных размерах шрифтов Understand named font sizes
- Отображение значков шрифтов Display font icons
Change the font size of all controls in the application (win forms)
I have an application that needs to be adaptive to a range of different screen sizes (resolutions). Most of that I’ve done using table layout panels.
But some of the control (buttons and labels mostly) have too large font and the text doesn’t fit in the control. So far I’ve managed change the font of some controls by using
But that is too much text to add for every single control in the application.
Is there a way of changing the fonts of all the controls on the application at once? Or at least all controls on a form?
2 Answers 2
A simple recursive function will traverse all the controls in your form and change the font size. You need to test it against your controls and look at the effect because in this code there is no exception handling
You can call it from your toplevel form passing the initial form’s control collection
Based on Steve’s good answer, I would do the following improvements:
This allows to grow or shrink the font size in percent like:
Or you can shrink the font size absolutely by a value of -4 like:
In both examples, all fonts will be affected by the change. You do not need to know the font family names, each control can have different ones.
Combined with this answer you can auto-scale fonts in your application based on Windows settings (which you can find if you right click on the desktop, then select Display settings, Scale and layout and modify the value «Change the size of text, apps, and other items» — in Windows 10 versions newer than build 1809 this is (re-)named as «Make everything bigger»):
You should also limit the size to a certain maximum/minimum, based on your forms layout, e.g.
Likewise this is true for absolute values — note that in the code there is already a limit set: Practically, a font cannot be smaller than 4 em — this is set as minimum limit (of course you can adapt that to your needs).
Как изменить шрифт и его цвет в Label
Адресная книга
Как очистить Label и изменить шрифт?
Здравствуйте! Скажите пожалуйста, как можно очистить компонент Label ? Добавлено через 41 минуту.
Как изменить шрифт Label на жирный (bold)?
Здравствуйте форумчане. подскажите пожалуйста как присвоить label1 = bold (жирный) Добавлено.
Как изменить шрифт и цвет заголовка окна?
Помогите, пожалуйста, мне надо изменить цвет и шрифт заголовка окна. Это можна изменить вобще?
label1.Font = new Font(«Tobota», 14, FontStyle.Italic);
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Как изменить цвет, шрифт и фон кнопки в MATLAB
как сделать так, чтобы вот на фоне этой кнопки была картинка? function new figure ( ‘MenuBar’.
Как увеличить шрифт и изменить цвет в шапке сайта
Здравствуйте! Делаю сайт на dle screw-pump.com.ru на базе шаблона GoodCompany все пока.
Как изменить шрифт и цвет фона на всех формах?
Как изменить шрифт и цвет фона на всех формах на C#? Сделали отдельную форму для настроек шрифта и.
Как изменить цвет фрагмента Label?
Как изменить цвет фрагмента Label (одного слова)? К примеру: Label1.Caption:= ‘Красный, синий.
Шрифты в Xamarin.Forms Fonts in Xamarin.Forms
По умолчанию Xamarin.Forms использует системный шрифт, определенный каждой платформой. By default, Xamarin.Forms uses a system font defined by each platform. Однако элементы управления, отображающие текст, определяют свойства, которые можно использовать для изменения этого шрифта: However, controls that display text define properties that you can use to change this font:
- FontAttributes Тип FontAttributes , который является перечислением с тремя элементами: None , Bold и Italic . FontAttributes , of type FontAttributes , which is an enumeration with three members: None , Bold , and Italic . Значение по умолчанию этого свойства равно None . The default value of this property is None .
- FontSize типа double . FontSize , of type double .
- FontFamily типа string . FontFamily , of type string .
Эти свойства поддерживаются объектами BindableProperty , то есть эти свойства можно указывать в качестве целевых для привязки и стилизации данных. These properties are backed by BindableProperty objects, which means that they can be targets of data bindings, and styled.
Задание атрибутов шрифта Set font attributes
Элементы управления, отображающие текст, могут задавать FontAttributes атрибуты шрифта для свойства: Controls that display text can set the FontAttributes property to specify font attributes:
Эквивалентный код на C# выглядит так: The equivalent C# code is:
Задать размер шрифта Set the font size
Элементы управления, отображающие текст, могут задать FontSize для свойства Размер шрифта. Controls that display text can set the FontSize property to specify the font size. FontSize Для свойства можно задать double значение напрямую или NamedSize значение перечисления: The FontSize property can be set to a double value directly, or by a NamedSize enumeration value:
Эквивалентный код на C# выглядит так: The equivalent C# code is:
Кроме того, Device.GetNamedSize метод имеет переопределение, которое указывает второй аргумент в качестве Element : Alternatively, the Device.GetNamedSize method has an override that specifies the second argument as an Element :
FontSize Значение, указанное как double , измеряется в единицах, не зависящих от устройства. The FontSize value, when specified as a double , is measured in device-independent units. Дополнительные сведения см. в разделе единицы измерения. For more information, see Units of Measurement.
Дополнительные сведения об именованных размерах шрифтов см. в разделе сведения о размерах шрифтов. For more information about named font sizes, see Understand named font sizes.
Задание семейства шрифтов Set the font family
Элементы управления, отображающие текст, могут задать FontFamily для свойства имя семейства шрифтов, например Times Roman. Controls that display text can set the FontFamily property to a font family name, such as «Times Roman». Однако это будет работать только в том случае, если семейство шрифтов поддерживается на конкретной платформе. However, this will only work if that font family is supported on the particular platform.
Существует ряд методов, с помощью которых можно попытаться получить шрифты, доступные на платформе. There are a number of techniques that can be used to attempt to derive the fonts that are available on a platform. Однако наличие файла шрифта TTF (формат типа true) не обязательно подразумевает семейство шрифтов, и часто включаются Ттфс, которые не предназначены для использования в приложениях. However, the presence of a TTF (True Type Format) font file does not necessarily imply a font family, and TTFs are often included that are not intended for use in applications. Кроме того, шрифты, установленные на платформе, могут измениться в версии платформы. In addition, the fonts installed on a platform can change with platform version. Таким образом, самым надежным подходом для указания семейства шрифтов является использование пользовательского шрифта. Therefore, the most reliable approach for specifying a font family is to use a custom font.
Пользовательские шрифты можно добавить в Xamarin.Forms общий проект и использовать в проектах платформы без дополнительной работы. Custom fonts can be added to your Xamarin.Forms shared project and consumed by platform projects without any additional work. Чтобы этого добиться, выполните следующие действия. The process for accomplishing this is as follows:
- Добавьте шрифт в Xamarin.Forms общий проект в качестве внедренного ресурса (действие сборки: EmbeddedResource). Add the font to your Xamarin.Forms shared project as an embedded resource (Build Action: EmbeddedResource).
- Зарегистрируйте файл шрифта в сборке в файле, например AssemblyInfo.CS, с помощью ExportFont атрибута. Register the font file with the assembly, in a file such as AssemblyInfo.cs, using the ExportFont attribute. Также можно указать необязательный псевдоним. An optional alias can also be specified.
В следующем примере показан Lobster-Regularный шрифт, регистрируемый в сборке вместе с псевдонимом: The following example shows the Lobster-Regular font being registered with the assembly, along with an alias:
Шрифт может находиться в любой папке в общем проекте без указания имени папки при регистрации шрифта в сборке. The font can reside in any folder in the shared project, without having to specify the folder name when registering the font with the assembly.
В Windows имя файла шрифта и имя шрифта могут отличаться. On Windows, the font file name and font name may be different. Чтобы обнаружить имя шрифта в Windows, щелкните TTF-файл правой кнопкой мыши и выберите Предварительный просмотр. To discover the font name on Windows, right-click the .ttf file and select Preview. Затем имя шрифта можно определить в окне предварительного просмотра. The font name can then be determined from the preview window.
Затем шрифт можно использовать на каждой платформе, ссылаясь на его имя, без расширения файла: The font can then be consumed on each platform by referencing its name, without the file extension:
Кроме того, его можно использовать на каждой платформе, ссылаясь на его псевдоним: Alternatively, it can be consumed on each platform by referencing its alias:
Эквивалентный код на C# выглядит так: The equivalent C# code is:
На следующих снимках экрана показан пользовательский шрифт: The following screenshots show the custom font:
Для сборок выпуска в Windows убедитесь, что сборка, содержащая пользовательский шрифт, передается в качестве аргумента в Forms.Init вызове метода. For release builds on Windows, ensure the assembly containing the custom font is passed as an argument in the Forms.Init method call. Дополнительные сведения см. в руководстве по устранению неполадок. For more information, see Troubleshooting.
Установка свойств шрифта для каждой платформы Set font properties per platform
OnPlatform Классы и On можно использовать в XAML для установки свойств шрифта для каждой платформы. The OnPlatform and On classes can be used in XAML to set font properties per platform. В приведенном ниже примере для каждой платформы устанавливаются разные гарнитуры и размеры шрифтов: The example below sets different font families and sizes on each platform:
Device.RuntimePlatform Свойство можно использовать в коде для задания свойств шрифта для каждой платформы The Device.RuntimePlatform property can be used in code to set font properties per platform
Дополнительные сведения о предоставлении значений для конкретной платформы см. в разделе Указание значений для конкретной платформы. For more information about providing platform-specific values, see Provide platform-specific values. Дополнительные сведения о OnPlatform расширении разметки см. в разделе расширение разметки для платформы. For information about the OnPlatform markup extension, see OnPlatform markup extension.
Общие сведения об именованных размерах шрифтов Understand named font sizes
Xamarin.Forms Определяет поля в NamedSize перечислении, представляющие определенные размеры шрифтов. Xamarin.Forms defines fields in the NamedSize enumeration that represent specific font sizes. В следующей таблице показаны NamedSize элементы и их размеры по умолчанию для iOS, Android и универсальная платформа Windows (UWP). The following table shows the NamedSize members, and their default sizes on iOS, Android, and the Universal Windows Platform (UWP):
Член Member | iOS iOS | Android Android | UWP UWP |
---|---|---|---|
Default | 17 17 | 14 14 | 14 14 |
Micro | 12 12 | 10 10 | 15,667 15.667 |
Small | 14 14 | 14 14 | 18,667 18.667 |
Medium | 17 17 | 17 17 | 22,667 22.667 |
Large | 22 22 | 22 22 | 32 32 |
Body | 17 17 | 16 16 | 14 14 |
Header | 17 17 | 96 96 | 46 46 |
Title | 28 28 | 24 24 | 24 24 |
Subtitle | 22 22 | 16 16 | 20 20 |
Caption | 12 12 | 12 12 | 12 12 |
Значения размера измеряются в единицах, не зависящих от устройства. The size values are measured in device-independent units. Дополнительные сведения см. в разделе единицы измерения. For more information, see Units of Measurement.
В iOS и Android именованные размеры шрифтов будут автоматически масштабироваться на основе специальных возможностей операционной системы. On iOS and Android, named font sizes will autoscale based on operating system accessibility options. Это поведение можно отключить в iOS с конкретной платформой. This behavior can be disabled on iOS with a platform-specific. Дополнительные сведения см. в разделе масштабирование специальных возможностей для именованных размеров шрифтов в iOS. For more information, see Accessibility Scaling for Named Font Sizes on iOS.
Отображение значков шрифтов Display font icons
Значки шрифтов могут отображаться Xamarin.Forms приложениями путем указания данных значка шрифта в FontImageSource объекте. Font icons can be displayed by Xamarin.Forms applications by specifying the font icon data in a FontImageSource object. Этот класс, производный от ImageSource класса, имеет следующие свойства: This class, which derives from the ImageSource class, has the following properties:
- Glyph — значение символа Юникода значка шрифта, указанного как string . Glyph – the unicode character value of the font icon, specified as a string .
- Size — double значение, указывающее размер (в единицах, независимых от устройства) значка отображаемого шрифта. Size – a double value that indicates the size, in device-independent units, of the rendered font icon. Значение по умолчанию — 30. The default value is 30. Кроме того, для этого свойства можно задать именованный размер шрифта. In addition, this property can be set to a named font size.
- FontFamily — Объект, string представляющий семейство шрифтов, которому принадлежит значок шрифта. FontFamily – a string representing the font family to which the font icon belongs.
- Color — необязательное Color значение, используемое при отображении значка шрифта. Color – an optional Color value to be used when displaying the font icon.
Эти данные используются для создания PNG-изображения, которое может отображаться в любом представлении, которое может отображать ImageSource . This data is used to create a PNG, which can be displayed by any view that can display an ImageSource . Такой подход позволяет отображать значки шрифтов, например эмодзи, в нескольких представлениях, в отличие от отображения значка шрифта в представлении одного текста, например Label . This approach permits font icons, such as emojis, to be displayed by multiple views, as opposed to limiting font icon display to a single text presenting view, such as a Label .
Значки шрифтов могут быть заданы только в символьном представлении в Юникоде. Font icons can only currently be specified by their unicode character representation.
В следующем примере XAML имеется один значок шрифта, отображаемый Image представлением: The following XAML example has a single font icon being displayed by an Image view:
Этот код отображает значок XBox из семейства шрифтов Иониконс в Image представлении. This code displays an XBox icon, from the Ionicons font family, in an Image view. Обратите внимание, что хотя символ Юникода для этого значка имеет значение \uf30c , он должен быть экранирован в XAML и, таким образом, стал . Note that while the unicode character for this icon is \uf30c , it has to be escaped in XAML and so becomes . Эквивалентный код на C# выглядит так: The equivalent C# code is:
На следующих снимках экрана из примера » связываемые макеты » показаны несколько значков шрифтов, отображаемых с помощью связываемого макета: The following screenshots, from the Bindable Layouts sample, show several font icons being displayed by a bindable layout: