迭代日期单元格并动态设置每个单元格的前景图像
for (int i = 0; i < numDatesSelected; i++) {
UIButton *myButton = (UIButton *)[self.smallCalendarView viewWithTag:[selectedDates[i] timeIntervalSince1970]];
float btnWidth = myButton.frame.size.width;
float btnHeight = (myButton.frame.size.height - (i*3));
UIImage *img = [self imageWithColor:[UIColor greenColor] width:btnWidth height:btnHeight];
[myButton setImage:img forState:UIControlStateNormal];
}
}
返回UIImage对象
- (UIImage *)imageWithColor:(UIColor *)color width:(float)w height:(float)h {
CGRect rect = CGRectMake(0, 0, w, h);
// Create a w by H pixel context
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[color setFill];
UIRectFill(rect); // Fill it with your color
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
结果就是这个
我想将所有绿色框放在每个表格单元格的底部。它们现在垂直居中。我该怎么做?谢谢!!
答案 0 :(得分:1)
我建议创建与按钮大小相同的图像,并只填充放置在所需位置的内部矩形。
- (UIImage *)imageWithColor:(UIColor *)color totalWidth:(float)tw totalHeight:(float)th filledWidth:(float)fw filledHeight:(float)fh {
CGRect rect = CGRectMake(0, 0, tw, th);
// Create a tw by th pixel context
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
//Create a inner rect to fill with your color
CGRect innerRect = CGRectMake(0 , th - fh, fw, fh);
[color setFill];
// Fill the inner rect with your color
UIRectFill(innerRect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}