如何显示带有动态创建的姓名首字母的头像图标 [英] How to display avatar icon with dynamically created name initials
问题描述
我有一个要求,通过传递名称,它应该返回一个化身 图标,其中包含该名称中所包含单词的首字母.例如:如果我通过约翰·亚伯拉罕(John Abraham),它将返回带有"JA"的图标.
I have a requirement that, by passing a name, it should return an avatar icon which contains the first letters of the words contained in that name. For instance: if I pass John Abraham, it should return an icon with 'JA'.
我需要在SAPUI5控件中使用该图标.我对此一无所知.如何实现呢?感谢您的帮助.
I need to use that icon in an SAPUI5 control. I do not have any idea on this. How to implement this? Any help is appreciated.
推荐答案
画布答案在正确的轨道上,但是在您的情况下,您需要一个可以分配给控件src
或icon
属性的数据URL.
The canvas answeres are on the right track, but in your case you need a data url that you can assign to your controls src
or icon
property.
以下示例中的generateAvatar
函数将名称(字符串)转换为图像数据url(在url中将图像包含为base64 gif).可以将数据URL分配给按钮"图标属性或UI5控件上的任何其他图像url属性.您甚至可以将其用作具有数据绑定的格式化程序功能,如以下示例所示.
The generateAvatar
function in the following example converts a name (string) to a image data url (contains the image as base64 gif in the url). The data url can be assigned to the Buttons icon property or any other image url property on a UI5 control. And you can even use it as a formatter function with databinding as in the following example.
var model = new sap.ui.model.json.JSONModel({
name: "John Doe"
});
new sap.m.Input({value:"{/name}", valueLiveUpdate:true}).setModel(model).placeAt("body");
new sap.m.Button({
icon:{path: "/name", formatter: generateAvatar},
text:"Hello"
}).setModel(model).placeAt("body");
function generateAvatar(name){
var initials = name.split(' ').map(function(str) { return str ? str[0].toUpperCase() : "";}).join('');
var canvas = document.createElement('canvas');
var radius = 30;
var margin = 5;
canvas.width = radius*2+margin*2;
canvas.height = radius*2+margin*2;
// Get the drawing context
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(radius+margin,radius+margin,radius, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = 'grey';
ctx.fill();
ctx.fillStyle = "white";
ctx.font = "bold 30px Arial";
ctx.textAlign = 'center';
ctx.fillText(initials, radius+5,radius*4/3+margin);
return canvas.toDataURL();
//The canvas will never be added to the document.
}
这篇关于如何显示带有动态创建的姓名首字母的头像图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!