我想将图像对齐(水平和垂直)以创建动画。动画很简单:心脏会在愤怒贝多的标志内“振动”,但他必须在那张图像中“居中”。
我正在尝试以下方法:
function Test(){
function foo1(){
return "foo";
}
this.bar = function () {
var foo = foo1();
console.log(foo);
};
}
var test = new Test();
test.bar();
但是当我构建应用程序时,它不会集中化。动画有效,但不是对齐。我想在纵向模式下在每个设备中进行对齐。
我看故事板,图像很好。我做错了什么?
答案 0 :(得分:0)
您必须使用屏幕midX和midY属性并减去图像的半宽和半高:
if let imageURL = NSURL(string:"http://i.stack.imgur.com/Xs4RX.jpg"), data = NSData(contentsOfURL: imageURL), image = UIImage(data: data), image2URL = NSURL(string:"https://graph.facebook.com/10203430834250391/picture?type=large"), data2 = NSData(contentsOfURL: image2URL), image2 = UIImage(data: data2) {
let imageView = UIImageView(frame: UIScreen.mainScreen().bounds)
imageView.image = image
imageView.contentMode = UIViewContentMode.ScaleAspectFit
let image2View = UIImageView(frame: CGRect(x: UIScreen.mainScreen().bounds.midX-100, y: UIScreen.mainScreen().bounds.midY-100, width: 200, height: 200))
image2View.image = image2
image2View.contentMode = UIViewContentMode.Center
imageView.addSubview(image2View)
imageView
}
如果您的图像与设备屏幕尺寸不同,则必须使用较大的图像框架midX减去较小的图像框架midX并对高度执行相同操作:
heartImg.frame = CGRectMake(angryBedousImg.frame.size.width / 2, angryBedousImg.frame.size.height / 2, heartImg.frame.size.width, heartImg.frame.size.height)
要
heartImg.frame = CGRectMake(angryBedousImg.frame.midX - heartImg.frame.midX, angryBedousImg.frame.midY - heartImg.frame.midY, heartImg.frame.size.width, heartImg.frame.size.height)
答案 1 :(得分:0)
试试这个:
这将使您的heartImage中心显示背景图像。
let yourImage = UIImage(named: "YourImageName")
let heartImg = UIImageView()
heartImg.image = yourImage
heartImg.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(heartImg)
self.view.addConstraint(NSLayoutConstraint(item: heartImg, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.yourLogoImage, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: heartImg, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.yourLogoImage, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: heartImg, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 40))
self.view.addConstraint(NSLayoutConstraint(item: heartImg, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 40))