【发布时间】:2017-08-06 04:55:36
【问题描述】:
在我的项目中,我尝试使用 UIBezierPath 裁剪图像,并通过使用 CAShapeLayer 和 setMask 操作轻松完成。在我的裁剪操作之后,输出是:
现在,我正在尝试拉伸输出图像并制作这个矩形大小的图像。为此,我使用一个函数并获取数组中的所有像素颜色,不包括具有清晰颜色的像素。为此,我使用此功能:
public func getRGBAs(fromImage image: UIImage, x: Int, y: Int, count: Int) -> [UIColor] {
var result = [UIColor]()
// First get the image into your data buffer
guard let cgImage = image.cgImage else {
print("CGContext creation failed")
return []
}
let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let rawdata = calloc(height*width*4, MemoryLayout<CUnsignedChar>.size)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let context = CGContext(data: rawdata, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
print("CGContext creation failed")
return result
}
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
// Now your rawData contains the image data in the RGBA8888 pixel format.
var byteIndex = bytesPerRow * y + bytesPerPixel * x
for _ in 0..<count {
let alpha = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 3, as: UInt8.self)) / 255.0
let red = CGFloat(rawdata!.load(fromByteOffset: byteIndex, as: UInt8.self)) / alpha
let green = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 1, as: UInt8.self)) / alpha
let blue = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 2, as: UInt8.self)) / alpha
byteIndex += bytesPerPixel
let aColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
if aColor != UIColor(red: 0, green: 0, blue: 0, alpha: 0){
result.append(aColor)
}
result.append(aColor)
}
free(rawdata)
return result
}
然后尝试创建新图像以获取矩形图像。这段代码是:
public func imageFromARGB32Bitmap(pixels:[UIColor], width:UInt, height:UInt)->UIImage {
let bitsPerComponent:UInt = 8
let bitsPerPixel:UInt = 32
assert(pixels.count == Int(width * height))
var data = pixels // Copy to mutable []
let providerRef = CGDataProvider(
data: NSData(bytes: &data, length: data.count * MemoryLayout<UIColor>.size)
)
let cgim = CGImage(
width: Int(width),
height: Int(height),
bitsPerComponent: Int(bitsPerComponent),
bitsPerPixel: Int(bitsPerPixel),
bytesPerRow: Int(width) * Int(MemoryLayout<UIColor>.size),
space: rgbColorSpace,
bitmapInfo: bitmapInfo,
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent
)
return UIImage(cgImage: cgim!)
}
出了什么问题,解决办法是什么?
【问题讨论】:
标签: swift crop image-resizing