从图中可以看出,这里的 rect
不受控制,只根据 UIImageView 的大小有关
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView * imgView = [[UIImageView alloc] initWithImage:[self viewImageFromColor:[UIColor redColor]
rect:CGRectMake(0, 0, 20, 20)]];
imgView.frame = CGRectMake(100, 100, 200, 200);
imgView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:imgView];
}
- (UIImage *)viewImageFromColor:(UIColor *)color rect:(CGRect)rect{
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}