@ Evgeny Ilyin. Eugene Ilyin's idea is the best. I wrote a version of Objective-C based on this solution.
Create a UIImage category and advertise two classes of methods in UIImage + YourCategory.h
+ (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect; + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius;
Inject methods in UIImage + YourCategory.m
// create image with your color + (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect { UIGraphicsBeginImageContext(imageRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, imageRect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } // get a rounded-corner image from UIImage instance with your radius + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius { CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0); rect.size = image.size; UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius]; [path addClip]; [image drawInRect:rect]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
Make your own UISearchBar in your ViewController
CGRect rect = CGRectMake(0.0, 0.0, 44.0, 30.0); UIImage *colorImage = [UIImage imageWithColor:[UIColor yourColor] withSize:rect]; UIImage *finalImage = [UIImage roundImage:colorImage withRadius:4.0]; [yourSearchBar setSearchFieldBackgroundImage:finalImage forState:UIControlStateNormal];
steveluoxin 12 Oct. '17 at 1:26 on 2017-10-12 01:26
source share