有没有办法获取在UIColor类别中设置backgroundColor的对象边界?
例如,我正在尝试从图像中应用UIColor,但我希望它能够相应地展开。相关的参考文献是否可以完成这或者最好在UIView类别中实现这样的方法吗?
以下是设置backgroundColor的方法:
+ (UIColor *)colorWithGradientStyle:(GradientStyle)gradientStyle andColors:(NSArray *)colors {
//Create our background gradient layer
CAGradientLayer *backgroundGradientLayer = [CAGradientLayer layer];
//Set the frame to our object's bounds
backgroundGradientLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
//To simplfy formatting, we'll iterate through our colors array and create a mutable array with their CG counterparts
NSMutableArray *cgColors = [[NSMutableArray alloc] init];
for (UIColor *color in colors) {
[cgColors addObject:(id)[color CGColor]];
}
switch (gradientStyle) {
case linearLeftToRight: {
//Set out gradient's colors
backgroundGradientLayer.colors = cgColors;
//Specify the direction our gradient will take
[backgroundGradientLayer setStartPoint:CGPointMake(0.0, 0.5)];
[backgroundGradientLayer setEndPoint:CGPointMake(1.0, 0.5)];
//Convert our CALayer to a UIImage object
UIGraphicsBeginImageContext(backgroundGradientLayer.bounds.size);
[backgroundGradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * backgroundColorImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIColor colorWithPatternImage:backgroundColorImage];
}
case linearTopToBottom:
default: {
//Set out gradient's colors
backgroundGradientLayer.colors = cgColors;
//Convert our CALayer to a UIImage object
UIGraphicsBeginImageContext(backgroundGradientLayer.bounds.size);
[backgroundGradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * backgroundColorImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIColor colorWithPatternImage:backgroundColorImage];
}
}
}
答案 0 :(得分:1)
无论您在何处放置此代码,都需要对视图的引用才能获得其边界。您可以将视图或边界作为参数传递,也可以将其作为UIView类或子类。
UIColor类仅用于创建颜色,它与渲染或定位颜色无关。这是UIView的工作。因此UIColor不是这个代码的地方。
我建议继承UIView并重写drawRect来绘制渐变。或者创建一个UIView方法,如:-(void)setBackgroundGradientWithStyle:(GradientStyle)gradientStyle colors:(NSArray *)colors
并将此代码放在那里。