The implementation of the circular avatar with text with IOS _ios

Source: Internet
Author: User

Here's how it works. Drawing of circular heads

Let's take a look at the effect chart

Analyze:

1, first is the need to draw a round head with background color

2, then the need to draw text

3, text is a part of the intercepted string

4, different strings, the background color of the circle is not the same

5. For both Chinese and English, a character in English is also counted as a character.

6, Text always center display

All right, so we can start drawing a few more points.

Look at the results of the final implementation

First of all, we need to customize a view as a custom avatar, in the view of the drawRect method of image rendering

@interface Roundheadview ()
@property (nonatomic, copy) NSString *title;//the title @property you want to draw
(Nonatomic, assign ) CGFloat colorpoint;//The user to compute the random value of the color
//Set text
-(void) Settitle: (NSString *) title;
@end
@implementation Roundheadview
-(Instancetype) initWithFrame: (cgrect) frame{
  self = [super Initwithframe:frame];
  if (self) {
    Self.backgroundcolor = [Uicolor clearcolor];
  }
  return self;
}
@end

First draw a circle with the background color

-(void) DrawRect: (cgrect) rect{
  
  //an opaque type of quartz 2D painting environment, the equivalent of a canvas, you can paint any of the above
   cgcontextref context = Uigraphicsgetcurrentcontext ();
   [Self caculatecolor];//compute color/
  
  * Draw Circle *
   /Cgcontextsetrgbfillcolor (context,_colorpoint, 0.5, 0.5, 1.0);/Set Fill Color The color is set randomly here, followed by the text to calculate the color
  
  //Fill circle, Borderless
  cgcontextaddarc (context, self.frame.size.width/2.0, self.frame.size.width/2.0, self.frame.size.width/2.0, 0, 2*M_PI, 0); Add a circle
  cgcontextdrawpath (context, kcgpathfill);//Draw Fill
  }

Got a round head without words

Next, we'll draw the text.

First you need to calculate the size of the text

Set the text in

-(void) Settitle: (NSString *) title{
  _title = [[self substringwithlendth:2 string:title] copy];
  [Self setneedsdisplay];//calls this method to repaint the view to invoke the DrawRect method
}

Intercepting text

/**
 intercept A string, intercept the string the first two men and English to handle the
 character length intercepted @param lengths (both men and English)
 @param string to intercept
 @return Returns the intercepted string
 *
/-(NSString *) Substringwithlendth: (int) length string: (NSString *) string{
  
  nsstring *copystr = [string copy];
  nsmutablestring *realstr = [[Nsmutablestring alloc] init];
  
  for (int i = 0; i < copystr.length. i++) {
    if (length = = 0) {break
      ;
    }
    Unichar ch = [Copystr characteratindex:0];
    if (0x4e00 < ch && CH < 0x9fff)//How to judge is Kanji
    {
      //If the man needs to do other processing can be done here
    }
    //If for Chinese characters
    [ Realstr appendstring:[copystr Substringwithrange:nsmakerange (i,1)]];
      
    length = length-1;
  }
  return realstr;
}
/** calculate the size of the text, in the drawing of the
 image, to ensure that the text is always in the image of the median
 text size can be calculated by themselves here is defined as the width of 1/3 I think it's more appropriate to use it. Of course
 you can define your own
 @return the width of the text
 * *
-(cgsize) caculatelablesize{
  Uilabel *lable = [[Uilabel alloc] initwithframe:cgrectzero];
  Lable.font = [Uifont fontwithname:@ "ARIAL-BOLDMT" size:self.frame.size.width/3.0];
  Lable.text = Self.title;
  [lable SizeToFit];
  Cgsize size = lable.frame.size;
  return size;
}

Finally got the title that needs to be drawn on the image

Another step is to define the background color of the image according to the pinyin of the text or something else. I'm going to use pinyin here.
The first thing to do is to get pinyin

/**
 get the man pinyin
 @param originalstr original Chinese characters
 @return man's whole spell * *
-(NSString *) Pinyin: (NSString *) originalstr{
  nsmutablestring *str = [Originalstr mutablecopy];
  Cfstringtransform ((cfmutablestringref) str, NULL, Kcfstringtransformmandarinlatin, NO);
  Cfstringtransform ((cfmutablestringref) str, NULL, Kcfstringtransformstripdiacritics, NO);
  return [str stringbyreplacingoccurrencesofstring:@ "" withstring:@ "];
}

According to the phonetic calculation color, then a color this method my own blind thinking of a color of course, you can define a method to calculate the color

/**
 random color
 filled round head based on the
 phonetic characters of the color/
-(void) caculatecolor{
  if (_title.length = 0) {
    return;
  }
  if (_title.length>1) {
    NSString *firststr = [_title substringwithrange:nsmakerange (0,1)];
    NSString *secondstr = [_title substringwithrange:nsmakerange (1, 1)];
    NSString *firstpinyin = [self pinyin:firststr];
    NSString *secondpinyin = [self pinyin:secondstr];
    Nsuinteger count = firstpinyin.length+secondpinyin.length;
    if (count>10) {
      count-=10;
      Self.colorpoint = count/10.0;
    } else{
      self.colorpoint = count/10.0
    }
  } else{
    NSString *firststr = [_title substringwithrange:nsmakerange (0,1)];
    NSString *firstpinyin = [self pinyin:firststr];
    Nsuinteger count = firstpinyin.length;
    Self.colorpoint = count/10.0;
  }

We're all in need of it. Can you draw the text directly or in the drawRect method?

-(void) DrawRect: (cgrect) rect{//an opaque type of quartz 2D painting environment, the equivalent of a canvas, you can paint any of the above cgcontextref context = Uigraphicsgetcurre
  Ntcontext (); [Self caculatecolor];//compute color/* Draw Circle */Cgcontextsetrgbfillcolor (context,_colorpoint, 0.5, 0.5, 1.0);//Set Fill Color//CGC Ontextsetrgbstrokecolor (context,red,green,blue,1.0),//Brush Line Color//fill circle, borderless cgcontextaddarc (context, self.frame.size.width/2.0, self.frame.size.width/2.0, self.frame.size.width/2.0, 0, 2*M_PI, 0);  Add a circle Cgcontextdrawpath (context, kcgpathfill);//Draw Fill * Write text//Cgcontextsetrgbfillcolor (context, 1, 0, 0, 1.0)//Set fill color nsdictionary* dic = [nsdictionary dictionarywithobjectsandkeys:[uifont fontwithname:@ "Arial-BoldMT"
  SIZE:SELF.FRAME.SIZE.WIDTH/3.0], Nsfontattributename,[uicolor whitecolor],nsforegroundcolorattributename, nil];
  Cgsize size = [self caculatelablesize];
  CGFloat X = (self.frame.size.width-size.width)/2.0;
  CGFloat Y = (self.frame.size.height-size.height)/2.0; [Self.title Drawinrect:cgrectmake (X,Y, Self.frame.size.width, Self.frame.size.width) withattributes:dic]; }

Test

Uilabel *label = [[Uilabel alloc] Initwithframe:cgrectmake (A, M,)];
Label.text = @ "text is different, background color will not be the same";
[Self.view Addsubview:label];
Nsarray *strs = @[@ "For me", @ "kind", @ "good", @ "H", @ "HC", @ "2 only", @ "haha", @ "intend to plan", @ "still have V", @ "haha"];
for (int i=0; i<10; i++) {
  Roundheadview *head = [[Roundheadview alloc] Initwithframe:cgrectmake (100+), 40 )];
  [head settitle:strs[i]];
  [Self.view Addsubview:head];
}

Summarize

All right, we're done here, have we all learned? I hope the contents of this article will be helpful to the iOS developers, if you have any questions, you can exchange messages. Thank you for your support to the cloud-dwelling community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.