How to use icon font with Jetpack Compose? - android-studio

in before xml in TextView we have
holder.binding.iconInfo.text = "&#x${iconValue}"
and set out icon font to it with typeface dose anyone can help same thing but with jetpack compose

The specific syntax you mention that can be used with TextViews is due to the fact that XML is used when defining layouts. That is an XML numeric character entity that specifies a character with its unicode value in hexadecimal notation.
So it is not related to TextViews, layouts, fonts or icons.
If you want to do the same with a String in Kotlin and the character value is dynamic, you can do something like this
val text = "${Char(iconValue)}"
In Compose a custom font can be defined either as part of your Theme -> Typography and then used as text style or you can define it directly like this
val fontFamily = FontFamily(
// If you have the font in resources
Font(R.font.my_font_normal, weight = FontWeight.Normal),
Font(R.font.my_font_bold, weight = FontWeight.Bold),
Font(R.font.my_font_italic, weight = FontWeight.Normal, style = FontStyle.Italic),
// If you are loading the font at runtime from a file
Font(File(...), weight = FontWeight.Normal),
// ...
)
// Use with Text composable
Text(text = text, fontFamily = fontFamily)

Related

tk.Text: Tag Font

Is there a way to get a proper Font instance out of a tag, so I can change just the size? I know I can dump it in tk.font.Font but that seems really inefficient.
for tag in self.tag_names():
#I need `f` to be a Font instance, not just a string
f = self.tag_cget(tag, 'font')
If you used font objects to create the tags, then you can get the font name from the tag and then use nametofont to convert it to an instance of tkinter.font.Font. However, this only works if the tag has a font associated with it, and if the font is a font object rather than shorthand notation (eg: ("Helvetica", 24, "bold")).
from tkinter.font import nametofont
...
for tag_name in self.tag_names():
font_name = self.tag_cget(tag_name, "font")
if font_name:
font = nametofont(font_name)
size = int(font.cget("size"))
font.configure(size = size + delta)
One method is to premake all of the Font instances and assign the instances to the applicable tag's font option. When you want to change the sizes, loop over the stored Font instances, and change their sizes directly. Every tag that uses your Font instances will change accordingly.

Draw shape over Text with Modifier in Jetpack Compose

I am trying to obfuscate some text with Jetpack Compose. Obviously, the blur modifier works wonders for this use case if you have Android 12.
My alternative for devices running a lower API version would be to simply draw a rectangle with a black colour over the text. I assumed this would be relatively easy with existing modifiers like graphicsLayer or drawBehind but I haven't been able to figure it out and I'm at a loss for ideas right now...
My current text composable looks like this:
Text(
modifier = if (blurText) {
Modifier.blur(16.dp, BlurredEdgeTreatment.Unbounded)
} else {
Modifier
},
text = textToObfuscate,
fontFamily = latoFontFamily,
fontWeight = FontWeight.W700,
fontSize = 16.sp,
color = black,
)
I could wrap the text in a Box and have another Box inside it to draw over the Text but that just seems useless and more work than should be necessary.
If anyone has any ideas on how to achieve this simply using a Modifier extension, that would be amazing!
You can use Modifier.drawWithContent as
Text(
modifier = if (blurText) {
Modifier.blur(16.dp, BlurredEdgeTreatment.Unbounded)
} else {
Modifier.drawWithContent {
drawContent()
drawRect(Color.Black)
}
},
text = "textToObfuscate",
fontWeight = FontWeight.W700,
fontSize = 16.sp,
)

Is it possible to use more than one custom font in an SVG?

I'm using the Univers LT 47 Condensed Light font in SVG. In some of the elements use the Univers LT 47 Condensed Bold font. The SVG is rendered correctly but when I print the SVG on a PDF none of the fonts are respected and a default font (Times) is used.
Later on, i figured out that with setting a (the?) font provider I'm able to use the standard font.
string fontUniverseLT47 = HttpContext.Current.Server.MapPath("fonts/lte50144.ttf"),
fontUniverseLT47Bold = HttpContext.Current.Server.MapPath("fonts/LT.ttf");
FontProvider provider = new FontProvider();
provider.AddFont(FontProgramFactory.CreateFont(fontUniverseLT47));
provider.AddFont(FontProgramFactory.CreateFont(fontUniverseLT47Bold));
SvgConverterProperties props = new SvgConverterProperties();
props.SetCharset("Windows-1252");
props.SetFontProvider(provider);
byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(svg);
using (MemoryStream ms = new MemoryStream(byteArray))
{
Image image = SvgConverter.ConvertToImage(ms, pdf, props);
image.SetPageNumber(pageNumber);
image.SetFixedPosition(llx, lly);
image.ScaleToFit(width, height);
doc.Add(image);
}
But now I'd like to use the bold font which cannot be set in CSS with font-weight : bold as it's a different PdfFont.
Is there a way how I can use the second, bold font in the SVG?

How to find bit length of text with specific font and font size

I'm developing NativeScript JavaScript code to create dynamic text marker for maps. I have the code working that creates a marker for a specific string. My next step is to take any given string, determine its height and width in bits, and create the marker sized to contain the text.
My problem is finding the size of the text, given the text string itself, the font size, and the font family.
It looks like getMeasuredWidth could work, except that the string must already be loaded on a page before that function will return a value. In my case, I simply need to compute the size; the text won't otherwise appear as such on a page (the text in the marker becomes an image).
Is there a way to do this?
var bmp = BitmapFactory.create(200);
bmp.dispose(function (b) {
try {
b.drawRect(
"100,34", // size
'0,0', // upper-left coordinate
KnownColors.Black, // border color
KnownColors.Cornsilk // fill color
);
b.writeText(
"Parking",
"2,25",
{ color: KnownColors.Black, size: 8, name: 'fontawesome-webfont', });
...
In the code above, the width of "100" of the bounding rectangle actually represents the bit width of "Parking" with a small amount of padding. What I want to does calculate the rectangle's height and width and not hard-code it.
Try this, finding label size without adding it to Page upon button click
export function onFindButtonTap(args: EventData) {
const button = <any>args.object;
const label = new Label();
label.text = "Hello, found my size?"
label.fontSize = 20;
(<any>label)._setupAsRootView(button._context);
label.onLoaded();
label.measure(0, 0);
console.log(`Width : ${label.getMeasuredWidth()} x Height : ${label.getMeasuredHeight()}`);
}
Playground Sample
Note: I didn't get a chance to test it with iOS yet, let me know if you hit any issues.

Custom font does not render correctly when using ShowText

I have a custom view in which I am trying to draw text using a Windows font (calibri.ttf). However, I am getting different behaviour between using the DrawString & ShowText functions.
I have embedded the font as part of the app (added it to the UIAppFonts list & set it's build action to Content) and I all works fine when I use the DrawString method from my custom UIView e.g.
Code
public override void Draw (System.Drawing.RectangleF rect)
{
base.Draw (rect);
DrawString("Calibri font via DrawString", new RectangleF(10, 10, 100, 100), UIFont.FromName("Calibri", 16f));
}
Result
However, if I attempt to draw the same text this time using ShowText it appears as if the font isn't encoding the text correctly, or the character mapping is wrong.
Code
public override void Draw (System.Drawing.RectangleF rect)
{
base.Draw (rect);
var ctx = UIGraphics.GetCurrentContext();
ctx.SelectFont("Calibri", 16f, MonoTouch.CoreGraphics.CGTextEncoding.FontSpecific);
ctx.ShowTextAtPoint(10, 10, "Calibri font via ShowText using SelectFont");
}
Result
UPDATE - Here is what I get if I use MacRoman encoding instead of FontSpecific:
I have also tried loading in the font manually and using that but then I get nothing at all, it's like it doesn't recognise the font e.g.
var fontPath = NSBundle.MainBundle.PathForResource("calibri", "ttf");
var provider = new CGDataProvider(fontPath);
var font = CGFont.CreateFromProvider(provider);
var ctx = UIGraphics.GetCurrentContext();
ctx.SetFont(font);
ctx.ShowTextAtPoint(10, 20, "Calibri font via ShowText using SetFont");
I know that DrawString is UIKit & ShowText is CG (Quartz) so I understand that there may be differences. However, from what I gathered the only difference with DrawString was it corrected the issue with the difference in Offset (CG being at the bottom left/UIKit being at the top left).
NOTE - The underlying problem I have is I need to use this font to draw text onto a layer via a custom CALayerDelegate. I don't have access to the DrawString function from in there, therefore, the only way I can see to draw the text is via ShowText. Alternative solutions are welcome!
This really looks like an encoding issue. Try using CGTextEncoding.MacRoman instead of CGTextEncoding.FontSpecific (even Arial wouldn't render, as expected, with FontSpecific).
UPDATE Oct 12th
a) your last code sample won't work because Apple doc specifically states not to use SetFont and ShowText together. Quote follow:
Quartz uses font data provided by the system to map each byte of the array through the encoding vector of the current font to obtain the glyph to display. Note that the font must have been set using CGContextSelectFont. Don’t use CGContextShowText in conjunction with CGContextSetFont.
b) the CGTextEncoding.MacRoman code works with several other iPhone-supplied fonts. I'm beginning to suspect it's something about the Calibri.ttf font itself that is not supported by iOS.

Resources