.h
#import <UIKit/UIKit.h>
@interface UIImage (Color)
+ (UIImage *) ly_imageWithColor:(UIColor *)color;
+ (UIImage *) ly_imageWithColor:(UIColor *)color Size:(CGSize)size;
- (UIImage *) ly_stretched;
@end
.m
#import "UIImage+Color.h"
@implementation UIImage (Color)
+ (UIImage *) ly_imageWithColor:(UIColor *)color {
return [UIImage ly_imageWithColor:color Size:CGSizeMake(4.0f, 4.0f)];
}
+ (UIImage *) ly_imageWithColor:(UIColor *)color Size:(CGSize)size
{
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [image ly_stretched];
}
- (UIImage *) ly_stretched
{
CGSize size = self.size;
UIEdgeInsets insets = UIEdgeInsetsMake(truncf(size.height-1)/2, truncf(size.width-1)/2, truncf(size.height-1)/2, truncf(size.width-1)/2);
return [self resizableImageWithCapInsets:insets];
}
@end
本文介绍了一种在iOS开发中使用UIColor创建UIImage的方法。通过自定义的类别扩展,可以指定颜色和大小来生成UIImage,这在需要创建纯色背景图片的场景下非常实用。文章提供了详细的代码实现,包括如何设置颜色填充、获取当前上下文、结束图像上下文等关键步骤。
1413

被折叠的 条评论
为什么被折叠?



