好的,我试图做的是改变某个图像的像素数据。我想使用每次循环作为进度条时向右移动的UIView。然而,正在发生的事情是屏幕在计算过程中冻结,直到完成后才会发生任何事情。状态栏时钟也不会更新。有没有办法将这些计算以某种方式移动到背景中并仍然使用屏幕空间?
func lock() {
let lockView = UIImageView(image: self.photoBackgroundView.image!)
var progressBar = UIView(frame: CGRectMake(-self.view.width,0,self.view.width,20)
let increment = progressBar.width/self.photoBackgroundView.width
var password = self.textField.text!
if password == "" {
password = " "
}
var currentIndex = 0
let imageRect = CGRectMake(0, 0, self.photoBackgroundView.image!.size.width,self.photoBackgroundView.image!.size.height)
UIGraphicsBeginImageContext(self.photoBackgroundView.image!.size)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextDrawImage(context, imageRect, self.photoBackgroundView.image!.CGImage)
for x in 0...Int(self.photoBackgroundView.image!.size.width) {
print(x)
progressBar.frame.origin.x += (CGFloat(x) * increment)
self.view.addSubView(progressBar)
for y in 0...Int(self.photoBackgroundView.image!.size.height) {
let pointColor = lockView.layer.colorOfPoint(CGPoint(x: x, y: y))
if currentIndex == Array(password.characters).count {
currentIndex = 0
}
let red = encrypt(pointColor.components.red, passwordChar: Array(password.characters)[currentIndex], currentIndex: currentIndex, x: x, y: y)
currentIndex++
if currentIndex == Array(password.characters).count {
currentIndex = 0
}
let green = encrypt(pointColor.components.green, passwordChar: Array(password.characters)[currentIndex], currentIndex: currentIndex, x: x, y: y)
currentIndex++
if currentIndex == Array(password.characters).count {
currentIndex = 0
}
let blue = encrypt(pointColor.components.blue, passwordChar: Array(password.characters)[currentIndex], currentIndex: currentIndex, x: x, y: y)
currentIndex++
CGContextSetRGBFillColor(context, red, green, blue, pointColor.components.alpha)
CGContextFillRect(context, CGRectMake(CGFloat(x), CGFloat(y), 1, 1))
}
}
CGContextRestoreGState(context)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
self.photoBackgroundView.image = newImage
self.slideView.addSubview(photoBackgroundView)
self.view.addSubview(self.slideView)
}
答案 0 :(得分:4)
答案 1 :(得分:1)
当您在主线程中进行繁重的计算时,您的屏幕或UI会冻结。主线程负责更新UI元素,当您在mainThread上执行繁重的工作时,它将阻止mainThread并冻结不推荐的UI。
默认情况下,您编写的任何代码都将在主线程上运行。您需要分别在后台线程中编写代码,以便mainThread和BGthread可以同时运行。
您可以使用NSOperationQueue或GCD(Grand Central Dispatch)轻松编写要在其他一些后台线程中运行的函数。
请按照this链接获取进一步说明。