Centering image and vertically in UISegmentControl ios?

44 views Asked by At

So I am trying to insert both image and text into a UISegmentControl .Now in this segmentControl I am looking to place image on top and text at its bottom.So I am using a category on UIImage to put title on it like below.However my image and text are still misplaced after a lot of efforts .Has anybody done this before correctly?Any help is appreciated.

 + (id)imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color
{

  UIFont *font = [UIFont fontWithName:@"Helvetica" size:16];
  CGSize expectedTextSize = [string sizeWithAttributes:@{NSFontAttributeName: font}];
  int width = expectedTextSize.width + image.size.width + 5;
  int height = MAX(expectedTextSize.height, image.size.width);
  CGSize size = CGSizeMake((float)width, (float)height);
  UIGraphicsBeginImageContextWithOptions(size, NO, 0);

  CGContextRef context = UIGraphicsGetCurrentContext();

  CGContextSetFillColorWithColor(context, color.CGColor);

  int fontTopPosition = (height + expectedTextSize.height) / 2;

  CGPoint textPoint = CGPointMake(image.size.width/2, fontTopPosition);

  [string drawAtPoint:textPoint withAttributes:@{NSFontAttributeName: font}];
  // Images upside down so flip them
  CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height);
  CGContextConcatCTM(context, flipVertical);

  CGContextDrawImage(context, (CGRect){ {50,0},{image.size.width-10,image.size.height-10}}, [image CGImage]);

  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}
1

There are 1 answers

1
matt On

I'm not going to rewrite your code for you, but I definitely want to show you the way out of the woods. Step one is to stop using CGContextDrawImage, as this is involving you in the complexities of "flipping" and transforms. You should get rid of all that. To draw an image into your image, just draw it! Use the UIImage method drawAtPoint: or (if you need to resize as you go) drawInRect:. Then you can easily place the image exactly where you want it.

I'm also concerned about the whole question of how big your ultimate image should be. You are creating your image's ultimate size:

CGSize size = CGSizeMake((float)width, (float)height);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);

So if the image is coming out the wrong size, you need to change how you are calculating that width and height. What I would suggest you do is just the opposite of what you are doing now. Instead of letting the image and the text tell you what to do, start with the size you really want for an image that will fit nicely into your segment, and then fit the image and text into it as you draw.