gpt4 book ai didi

iOS:在 UIColor 类别中为 -colorWithPatternImage: 抓取对象的边界?

转载 作者:行者123 更新时间:2023-11-29 02:43:39 26 4
gpt4 key购买 nike

有没有办法获取在 UIColor 类别中设置背景颜色的对象的边界?

例如,我尝试从图像应用 UIColor,但我希望它相应地拉伸(stretch)。关联的引用文献会完成这项工作吗?或者最好在 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];
}

}

最佳答案

无论将这段代码放在哪里,都需要对 View 的引用以获得其边界。您可以将 View 或边界作为参数传递,也可以将其放入 UIView 类别或子类。

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

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

关于iOS:在 UIColor 类别中为 -colorWithPatternImage: 抓取对象的边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com