Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display avatar icon with dynamically created name initials

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'.

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.

like image 912
vijayalalitha Avatar asked Oct 18 '25 15:10

vijayalalitha


2 Answers

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.

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.
}

Example on JSBin

like image 194
schnoedel Avatar answered Oct 20 '25 05:10

schnoedel


Since UI5 1.46.x, such avatar icon controls are available out of the box.

<Avatar xmlns="sap.m"|"sap.f"*
  initials="{ path: 'name', formatter: '.createInitials' }"
  displayShape="Square"
/>

* sap.f if UI5 version is lower than 1.73. Otherwise, use the Avatar from sap.m instead!

createInitials: function(name) { // minimal sample
  return name.split(" ").map(str => str[0]).join("");
},

OpenUI5 Avatar control with initials

More samples can be found in https://openui5.hana.ondemand.com/entity/sap.m.Avatar.

like image 33
Boghyon Hoffmann Avatar answered Oct 20 '25 07:10

Boghyon Hoffmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!