2011-11-22 67 views
0

如何获得图像高度和宽度的计算?我试图像第一个答案说明中心的图像:SilverStripe获取图像宽度/高度的一半

How to make an image center (vertically & horizontally) inside a bigger div

这是我迄今为止尝试:

<% control ProfileImage %> 
    <% if getOrientation = 1 %> 
     <img src="$URL" style="margin-left: -{$Width/2)}px" class="portrait"/> 
    <% else_if getOrientation = 2 %> 
     <img src="$URL" class="landscape"/> 
    <% end_if %> 
<% end_control %> 

决定性线的输出是:

<img src="/assets/Uploads/picture.jpg" style="margin-left: -{154/2)}px" class="portrait"/> 

然后我试着写一个自己的功能:

class Profile extends Page{ 
//... 
function GetHalfWidth(){ 
    return ($this->ProfileImage->Width)/2; 
} 
//... 
} 

,但我得到以下错误,当我尝试在前台查看页面:

[Notice] Trying to get property of non-object 

回答

2

要获取模型图像的宽度,你可以改变你的函数如下:

function GetHalfWidth() { 
    $width = $this->obj('ProfileImage')->Width; 
    return $width/2; 
} 

但是,如果你正在尝试引用ProfileImage的控制环路内的方法,形式则需要“跳出”,并使用$ Top.GetHalfWidth

我想一个更好的方式来处理它会是将其定义为您的ProfileImage的方法,如果ProfileImage从图片的子类...

Profile.php

<?php 
class Profile extends Page { 

    ... 

    public static $has_one = array(
     'ProfileImage' => 'Profile_Image' 
    ); 

    ... 
} 
class Profile_Controller extends Page_Controller { 
    ... 
} 
class Profile_Image extends Image { 

    function GetHalfWidth() { 
     $width = $this->Width; 
     return $width/2; 
    } 

}