0

有没有办法抓住一个对象的边界,谁的 backgroundColor 被设置在 UIColor 类别中?

例如,我正在尝试从图像中应用 UIColor,但我希望它相应地被拉伸。相关的参考文献可以完成这项工作吗?或者最好在 UIView 类别中实现这种方法?

更新:

这是设置背景颜色的方法:

+ (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];
    }

}

}

4

1 回答 1

1

不管你把这段代码放在哪里,你都需要一个对视图的引用来获得它的边界。您可以将视图或边界作为参数传递,也可以将其作为 UIView 类别或子类。

UIColor 类仅用于创建颜色,与渲染或定位无关。这是 UIView 的工作。因此 UIColor 不是这个代码恕我直言的地方。

我建议继承 UIView 并覆盖 drawRect 来绘制渐变。或者创建一个 UIView 方法,例如:-(void)setBackgroundGradientWithStyle:(GradientStyle)gradientStyle colors:(NSArray *)colors并将这段代码放在那里。

于 2014-08-20T23:40:41.127 回答