我正在制作一款游戏,通过逐渐用健康宇宙飞船中的一个替换一个健康宇宙飞船的图像来显示对玩家宇宙飞船的损害,这是以&#34的方式;前/后"滑块。我试图找出如何实现这一点。
我尝试的方法是使用受损的太空船作为背景,然后在其上放置另一个UIView(或UIImageView),并且在损坏完成后,逐步限制顶视图的框架
这是我用来逐渐显示较少顶部图片的代码:
let oldFrame = playerLayer1.frame
let oldOrigin = oldFrame.origin
let newSize = CGSize(width: oldFrame.width - amountToReduceFrameBy, height: oldFrame.height)
let newFrame = CGRect(origin: oldOrigin, size: newSize)
playerLayer1.frame = newFrame
两个问题:
1)这只会使我的图像向左移动,而不是逐渐遮挡它。我试图减少视图的大小,使其只有部分可见,而不移动或重新缩放图像本身。我该怎么做
2)这是解决这个问题的正确方法吗?有更优雅的方式吗?
答案 0 :(得分:0)
解决:
func cropToWidth(image: UIImage, width: Double) -> UIImage {
let contextImage: UIImage = UIImage(CGImage: image.CGImage!)
let contextSize: CGSize = contextImage.size
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
// these vars represent original sizes, not specified ones
var cgwidth: CGFloat = contextSize.width
var cgheight: CGFloat = contextSize.height
// See what size is longer and create the center off of that
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
//let rect: CGRect = CGRectMake(posX, posY, cgwidth, cgheight)
let rect: CGRect = CGRectMake(posX, posY, CGFloat(width), cgheight)
print("rect dimensions: \(rect.width), \(rect.height)")
// Create bitmap image from context using the rect
let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)!
// Create a new image based on the imageRef and rotate back to the original orientation
let image: UIImage = UIImage(CGImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}