How to create text inside marker with google_maps_flutter? - flutter

How to implement a marker on Google Maps flutter with text on the marker. Image for reference:
https://i.stack.imgur.com/W6oqG.jpg

I managed to solve with this method
Future<BitmapDescriptor> createCustomMarkerBitmap(String title) async {
TextSpan span = new TextSpan(
style: new TextStyle(
color: Prefs.singleton().getTheme() == 'Dark'
? Colors.white
: Colors.black,
fontSize: 35.0,
fontWeight: FontWeight.bold,
),
text: title,
);
TextPainter tp = new TextPainter(
text: span,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
tp.text = TextSpan(
text: title.toStringAsFixed(0),
style: TextStyle(
fontSize: 35.0,
color: Theme.of(context).accentColor,
letterSpacing: 1.0,
fontFamily: 'Roboto Bold',
),
);
PictureRecorder recorder = new PictureRecorder();
Canvas c = new Canvas(recorder);
tp.layout();
tp.paint(c, new Offset(20.0, 10.0));
/* Do your painting of the custom icon here, including drawing text, shapes, etc. */
Picture p = recorder.endRecording();
ByteData pngBytes =
await (await p.toImage(tp.width.toInt() + 40, tp.height.toInt() + 20))
.toByteData(format: ImageByteFormat.png);
Uint8List data = Uint8List.view(pngBytes.buffer);
return BitmapDescriptor.fromBytes(data);
}
how to use:
BitmapDescriptor bitmapDescriptor = await createCustomMarkerBitmap(...);
Marker marker = Marker(
/* in addition to your other properties: */
icon: bitmapDescriptor
);

You can either do it manually using Canvas and Painter. Or you could use this package which does the exact same thing asked in the question.
https://pub.dev/packages/label_marker
Just go through the overview once and you can see if it is for you or not. I really hope it helps. And yeah. I made it :)

Related

Make CupertinoIcon render and not show placeholder

Based on this SO question, I tried to draw a CupertinoIcon on a Canvas:
final icon = CupertinoIcons.add;
TextPainter textPainter = TextPainter(
textDirection: TextDirection.ltr
);
textPainter.text = TextSpan(
text: String.fromCharCode(
icon.codePoint
),
style: TextStyle(
fontSize: 40.0,
fontFamily: icon.fontFamily
)
);
textPainter.layout();
textPainter.paint( canvas, Offset( params.x, params.y ) );
Note that the code is fully generic, since it uses properties like codePoint of the CupertinoIcon.
While this code renders the other painter commands, the code unfortunately renders a placeholder of the icon in Google Chrome:
How do I make the icon appear?
The icon appears, as soon as the package parameter gets added to TextStyle:
TextStyle(
fontSize: 60.0,
fontFamily: icon.fontFamily,
color: Colors.red,
package: icon.fontPackage // Need to make the icon appear
)
The documentation says this:
To use a font family defined in a package, the package argument must be provided.

How to draw a text inside rectangle in flutter

Hi I want to draw a filled rect with a text inside using canvas.
This is my code:
Rect rect = Rect.fromLTWH(x,y,size,size,);
Paint paint = Paint()..color = Colors.blue;
canvas.drawRRect(RRect.fromRectAndRadius(rect, Radius.circular(100.0)),paint,);
I don't know how to put a text inside a rect. Please help
Use TextPainter class.
You can play around with the offset yourself
TextPainter painter;
painter = TextPainter(
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
painter.text = TextSpan(
text: 'Sample Text',
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
),
);
Offset position = Offset(
x+2.0,
y+2.0,
);
painter.layout();
painter.paint(canvas, position);

Flutter: how to paint a Font Awesome Icon?

I am using CustomPainter to draw in flutter as per this question: Flutter: How to paint an Icon on Canvas?
final icon = Icons.cake;
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(fontSize: 20.0, fontFamily: icon.fontFamily));
textPainter.layout();
textPainter.paint(canvas, Offset(200.0, 200.0));
This works for Material Design Icons. However I would like to use the same techniqe to paint Font Awesome Icons. I am using the font_awesome_flutter 8.5.0 package, and this is my code:
final icon = Icon(FontAwesomeIcons.fish, size: 20, color: Colors.teal[700]);
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(fontSize: 20.0, fontFamily: icon.fontFamily));
textPainter.layout();
textPainter.paint(canvas, Offset(200.0, 200.0));
I am getting a message from the IDE saying that "The getter 'codePoint' isn't defined for the class 'Icon'". How can I fix this please?
Thanks to #pskink for helping me figure out this answer:
final fishCodePoint = FontAwesomeIcons.fish.codePoint;
print('The codePoint is $fishCodePoint');
final fishFontPackage = FontAwesomeIcons.fish.fontPackage;
print('The fontPackage is $fishFontPackage');
final fishFontFamily = FontAwesomeIcons.fish.fontFamily;
print('The fontFamily is $fishFontFamily');
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(fishCodePoint),
style: TextStyle(
fontSize: 40.0,
fontFamily: fishFontFamily,
package: fishFontPackage));
textPainter.paint(canvas, Offset(50.0, 50.0));

How can I change the color of several words in the TextField Widget?

Im trying to do chat mentions and I need to some how change the color of full name that mentioned in the TextField before send the message.
How can I do that?
Hope i'm not too late :)
I had the same issue and couldn't find any implementation in the main flutter package or any third party packages, so i hacked a little packaage and uploaded it.
it's an extension of the text editing controller that you can supply with a map of Regex patterns and corresponding Text style.
https://pub.dev/packages/rich_text_controller
https://github.com/micwaziz/rich_text_controller
In case someone stumbles across this question (like I did) but requires the textfield to render tap-able links, then here's one way to do it (simplified from our final implementation for better clarity). It's inspired by the RichTextController, but with the definitive focus to allow for taps on the links.
Regarding the regular expression: We tried using linkify, but despite trying all options, it tended to modify the links - which messed up the user input.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
class LinkedTextEditingController extends TextEditingController {
final RegExp linkRegexp;
final TextStyle linkStyle;
final Function(String match) onTap;
static RegExp _defaultRegExp =
RegExp(r'((?:(https?:\/\/)?)(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,5}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))', caseSensitive: false, dotAll: true);
static void _defaultOnLaunch(String url) async {
final re = RegExp('^https?://');
final fullUrl = re.hasMatch(url) ? url : 'http://$url';
if (await canLaunch(fullUrl)) {
await launch(fullUrl);
}
}
LinkedTextEditingController({
String text,
RegExp regexp,
this.linkStyle,
this.onTap = _defaultOnLaunch,
}) : linkRegexp = regexp ?? _defaultRegExp,
super(text: text);
LinkedTextEditingController.fromValue(
TextEditingValue value, {
RegExp regexp,
this.linkStyle,
this.onTap = _defaultOnLaunch,
}) : linkRegexp = regexp ?? _defaultRegExp,
assert(
value == null || !value.composing.isValid || value.isComposingRangeValid,
'New TextEditingValue $value has an invalid non-empty composing range '
'${value.composing}. It is recommended to use a valid composing range, '
'even for readonly text fields',
),
super.fromValue(value ?? TextEditingValue.empty);
#override
TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
List<TextSpan> children = [];
text.splitMapJoin(
linkRegexp,
onMatch: (Match match) {
children.add(
TextSpan(
text: match[0],
style: linkStyle,
recognizer: onTap == null ? null : TapGestureRecognizer()
..onTap = () => onTap(match[0]),
),
);
return null;
},
onNonMatch: (String span) {
children.add(TextSpan(text: span, style: style));
return span;
},
);
return TextSpan(style: style, children: children);
}
}
as Durdu suggested, you can use RichText to achieve different color text. Just need to put multiple TextSpan with different color using TextStyle. Sample as below
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0, bottom: 10.0),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
children: [
TextSpan(
text: 'By clicking sign up, you have read and agreed to our ',
style: TextStyle(color: Colors.black54),
),
TextSpan(
text: 'Terms & Conditions',
style: TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()
..onTap = () {
print('Tapped on hyperlink');
},
),
TextSpan(
text: '.',
style: TextStyle(color: Colors.black54),
),
],
),
),
),
Hope this clears and solve your problem.
If you just want to change the color or font for the text in the textfield:
Text("Hello",
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w900))
If you want to use multiple styles you should check, you should check RichText.
The RichText widget displays text that uses multiple different styles.
RichText(
text: TextSpan(
text: 'Hello ',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w900)),
children: <TextSpan>[
TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: ' world!'),
],
),
)

Drawing text in a specific spot using flutter

For text drawing on canvas, a fairly simple construction can be used:
void drawName(Canvas context, String name, double x, double y)
{
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: name);
TextPainter tp = new TextPainter(
text: span, textAlign: TextAlign.left, textDirection: `
` TextDirection.ltr);
tp.layout();
tp.paint(context, new Offset(x, y));
}
Is it possible to draw text at an angle, for example 45 degrees, or 90 degrees (vertically from the bottom up)?
To rotate text on a canvas, you can use canvas transforms rather than rotating the entire canvas.
That looks something like this:
#override
void paint(Canvas canvas, Size size) {
// save is optional, only needed you want to draw other things non-rotated & translated
canvas.save();
canvas.translate(100.0, 100.0);
canvas.rotate(3.14159/4.0);
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: "text");
TextPainter tp = new TextPainter(
text: span, textDirection: TextDirection.ltr);
tp.layout();
tp.paint(canvas, new Offset(0.0, 0.0));
// optional, if you saved earlier
canvas.restore();
}
Note that I'm translating then rotating, because if you translate after or even use the offset you'll probably get a different result than what you want. Also, once you start using transforms (translate & rotate) you probably want to save the transform state and then restore after you draw whatever you want transformed, at least if you're drawing anything other than the rotated text.
It sounds like you are looking for a Transformation. There is a general Transform Widget, but there is also a more specific RotatedBox Widget that sounds like it will be a perfect fit for you.
new RotatedBox(
quarterTurns: 3,
child: const Text('Hello World!'),
)
If you need more control over the rotation (to use something other than 90 degree increments) you should be able to achieve this the Transform Widget and a Matrix4.rotationZ
new Container(
color: Colors.blue,
child: new Transform(
transform: new Matrix4.rotationZ(-0.785398),
child: new Container(
padding: const EdgeInsets.all(8.0),
color: const Color(0xFFE8581C),
child: const Text('Apartment for rent!'),
),
),
)
A function that draws text at a specified angle:
void drawText(Canvas context, String name, double x, double y, double angleRotationInRadians)
{
context.save();
context.translate(x, y);
context.rotate(angleRotationInRadians);
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: name);
TextPainter tp = new TextPainter(
text: span, textAlign: TextAlign.left,
textDirection: TextDirection.ltr);
tp.layout();
tp.paint(context, new Offset(0.0,0.0));
context.restore();
}
PS."rmtmckenzie", thank a lot for your help.