嘿,我是编程新手,我想知道是否可以创建 UInt32 类型的具有 2 种颜色(例如红色和蓝色)的渐变效果。 有什么建议么?谢谢
问题补充
这个想法是我只有像素信息:
func fillRegion(pixelX: Int, pixelY: Int, withColor color: UIColor) {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let newColor = (UInt32)(alpha*255)<<24 | (UInt32)(red*255)<<16 | (UInt32)(green*255)<<8 | (UInt32)(blue*255)<<0
let pixelColor = regionsData.advanced(by: (pixelY * imageHeight) + pixelX).pointee
if pixelColor == blackColor { return }
var pointerRegionsData: UnsafeMutablePointer<UInt32> = regionsData
var pointerImageData: UnsafeMutablePointer<UInt32> = imageData
var pixelsChanged = false
for i in 0...(imageHeight * imageHeight - 1) {
if pointerRegionsData.pointee == pixelColor {
pointerImageData = imageData.advanced(by: i)
if pointerImageData.pointee != newColor {
pointerImageData.pointee = newColor
pixelsChanged = true
}
}
pointerRegionsData = pointerRegionsData.successor()
}
if pixelsChanged {
self.image = UIImage(cgImage: imageContext.makeImage()!)
DispatchQueue.main.async {
CATransaction.setDisableActions(true)
self.layer.contents = self.image.cgImage
self.onImageDraw?(self.image)
}
self.playTapSound()
}
}
现在它填充了简单的颜色,但我需要以某种方式设置渐变,我没有正确的形式,并且我无法设置 CAShapeLayer...因为我只有像素数信息和他的颜色,尽管我可以在这里更改颜色:
if pointerImageData.pointee != newColor {
pointerImageData.pointee = newColor
pixelsChanged = true
}
但我不知道如何平滑地改变颜色,制作渐变效果,或者以某种方式识别周长并设置图层,不知道,任何想法都会像金子一样。
最佳答案
是的,可以使用CoreGraphics
或CALayer
。
为了简化,您可以覆盖返回 CAGradientLayer 的 View 的图层。
这是一个实现:
@implementation PGSGradientView
+ (Class)layerClass {
return [CAGradientLayer class];
}
- (instancetype) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initializeGradient];
}
return self;
}
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initializeGradient];
}
return self;
}
- (void) initializeGradient {
[(CAGradientLayer*)self.layer setLocations:locations];
[(CAGradientLayer*)self.layer setColors:colors];
}
@end
假设您有 2 个数组作为属性,一个是 locations
,另一个是您要在渐变中添加的 colors
。
locations
代表:
the starting location for each color. Also, and that’s important, those numbers should mandatorily range from 0.0 to 1.0. and is paired with the colors arrays.
关于ios - UInt32 颜色的渐变效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849669/