65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP Image Control 增强

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

8分钟阅读

viewsIcon

5704

在 ScriptControl 和 JavaScript 的帮助下增强 ASP Image Control。当我开始作为一名 ASP.NET Web 开发者工作时,我一直受到它的困扰

在 ScriptControl 和 JavaScript 的帮助下增强 ASP Image Control。

当我开始作为一名 ASP.NET Web 开发者工作时,我一直受到 HTML 的局限性困扰。

后来在我工作中出现问题的其中一个局限性是如何在一个固定大小的容器(例如幻灯片照片框或照片网格)中正确拉伸一个比例未知(未知比例)的图片。你需要提前知道图片的正确尺寸才能设置 img 标签的正确宽度或高度,否则图片比例会失调或无法适应其容器(全尺寸)。

我决定用 JavaScript 来解决这个问题。但问题是,我应该只解决一次还是做一个更通用的东西?我决定,如果我能做到通用,我将永远不必再关心这个问题,所以它值得稍微长一点的开发时间。

我创建了一个自定义控件,它扩展了 Image 控件并实现了 IScriptcontrol。它可以正确地拉伸图片,可以将图片居中到其容器中,并且当图片很大需要一段时间才能完全加载时,还可以显示加载图片。

此控件可以轻松地在 aspx 页面中使用,进行数据绑定,对我来说它非常有用,我决定与 Asp.net 社区分享。它是一个扩展的 ImageContol,同时也是一个 ScriptControl。 

附注. 重要 当图片小于容器时,它们仍会被拉伸。这个很容易修复并添加到我的代码中,但我现在没有时间这样做。

<code language="C#" name="myImageControl.cs">

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;


[assembly: System.Web.UI.WebResource("Controls.myImage.js", "text/javascript")]
namespace Controls
{
    /// <summary>

    /// ContainerHeight:您希望此照片调整到的容器的高度

    /// ContainerWidth:您希望此 img 调整到的容器的宽度。

    /// HorizontalCentered:如果希望图片在其容器中水平居中,则设置为 true。

    /// VerticalCentered:如果希望图片在其容器中垂直居中,则设置为 true。

    /// LoadImgId:页面上显示加载图片的元素(gif 动画或类似效果)的 ClientID。此 img 在实际图片加载期间显示(如果它是非常大的图片)

    /// LoadImgWidth:加载图片的宽度(我懒得即时检查加载图片的尺寸,因为此图片尺寸通常是提前知道的,如果未设置,加载图片将无法正确居中到容器中)。

    /// LoadImgHeight:加载图片的高度。

    /// ImageUrlExt:使用此项为图片设置图片 URL。

    /// 重要!不要使用 ImageUrl 属性,而应使用 ImageUrlExt。原因是我们需要控制客户端何时设置图片 src 属性!

    /// </summary>

    [ToolboxData("<{0}:myImageControl runat=server></{0}:myImageControl>")]
    public class myImage : Image, INamingContainer, IScriptControl
    {

        int _containerHeight;
        //容器高度
        public int ContainerHeight
        {
            get { return _containerHeight; }
            set { _containerHeight = value; }
        }

        int _containerWidth;
        //容器宽度
        public int ContainerWidth
        {
            get { return _containerWidth; }
            set { _containerWidth = value; }
        }

        string _imageUrlExt;
        //始终使用此扩展的 ImageURL
        public string ImageUrlExt
        {
            get { return _imageUrlExt; }
            set { _imageUrlExt = value; }
        }       

        public override string ImageUrl
        {
            get
            {
                return base.ImageUrl;
            }
            set
            {
                base.ImageUrl = "";
            }
        }

        bool _horizontalCentered;

        public bool HorizontalCentered
        {
            get { return _horizontalCentered; }
            set { _horizontalCentered = value; }
        }

        bool _verticalCentered;

        public bool VerticalCentered
        {
            get { return _verticalCentered; }
            set { _verticalCentered = value; }
        }

        string _loadImgId;

        public string LoadImgId
        {
            get { return _loadImgId; }
            set { _loadImgId = value; }
        }

        int _loadImgHeight;

        public int LoadImgHeight
        {
            get { return _loadImgHeight; }
            set { _loadImgHeight = value; }
        }

        int _loadImgWidth;

        public int LoadImgWidth
        {
            get { return _loadImgWidth; }
            set { _loadImgWidth = value; }
        }


        private ScriptManager _scriptManager = null;

        protected override void OnLoad(EventArgs e)
        {

            _scriptManager = ScriptManager.GetCurrent(this.Page);

            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {            

            _scriptManager = ScriptManager.GetCurrent(this.Page);
            if (_scriptManager != null)
            {
                _scriptManager.RegisterScriptControl(this);
            }
            else
                throw new ApplicationException("必须有 ScriptManager!");

            base.OnPreRender(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {           
            _scriptManager.RegisterScriptDescriptors(this);

            base.Render(writer);
        }


        #region IScriptControl 成员

        public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor = new ScriptControlDescriptor("Controls.myImage", this.ClientID);
            descriptor.AddProperty("containerWidth", this.ContainerWidth);
            descriptor.AddProperty("containerHeight", this.ContainerHeight);
            descriptor.AddProperty("elementId", this.ClientID);
            descriptor.AddProperty("imageUrl", this.ImageUrlExt);
            descriptor.AddProperty("horizontalCentered", this.HorizontalCentered);
            descriptor.AddProperty("verticalCentered", this.VerticalCentered);            
            if(!string.IsNullOrEmpty(this._loadImgId))
                descriptor.AddElementProperty("loadImg", this._loadImgId);
            descriptor.AddProperty("loadImgWidth", this._loadImgWidth);
            descriptor.AddProperty("loadImgHeight", this._loadImgHeight);

            return new ScriptDescriptor[] { descriptor };
        }

        public IEnumerable<ScriptReference> GetScriptReferences()
        {
            ScriptReference reference = new ScriptReference();
            reference.Path = Page.ClientScript.GetWebResourceUrl(typeof(myImage), "Controls.myImage.js");

            return new ScriptReference[] { reference };
        }

        #endregion
    }
}

</code>

JavaScript 代码如下: 

<code language="js" src="myImage.js">


Type.registerNamespace('Controls');


Controls.myImage = function(element)

{

    

    Controls.myImage.initializeBase(this, [element]);   

    

    this._containerHeight = 0;

    

    this._containerWidth = 0;

    

    this._horizontalCentered = null;

    

    this._verticalCentered = null;

    

    this._elementId = '';

    

    this._onLoadHandler = null;


    this._imageUrl = '';

    

    this._onClick = null;

    

    this._loadImg = null;

    

    this._loadImgWidth = 0;

    

    this._loadImgHeight = 0;

    

    this._loadImgCopy = null;

 

};


Controls.myImage.prototype =

{


    initialize : function() {

    

        // 初始化基类

        Controls.myImage.callBaseMethod(this,'initialize');   

    

        //在图片开始加载之前设置事件处理程序!

        this._onLoadHandler = Function.createDelegate(this,this._OnLoad)

        this._onFocusHandler = function(){};

        

        

        $addHandler(this.get_element(),'load', this._onLoadHandler);

        $addHandler(this.get_element(),'focus', this._onFocusHandler);

                     

        this._LoadImage();

        

    },

    

    _setLoadingImage : function()

    {

        this._removeLoadingImage();

        

        if(this._loadImg && this._imageUrl && this._imageUrl != '')

        {

            var element = $get(this._elementId);            

            this._loadImgCopy = this._loadImg.cloneNode(false);            

            this._loadImgCopy.id = this._elementId+'_loadImgInstance';

            this._loadImgCopy.style.display='';

            this._loadImgCopy.style.visibility ='visible';

            

            var hspace = (this._containerWidth - this._loadImgWidth)/2;            

            this._loadImgCopy.setAttribute('hspace',Math.floor(hspace));

            

            var vspace = (this._containerHeight - this._loadImgHeight)/2;

            this._loadImgCopy.setAttribute('vspace',Math.floor(vspace));

            

            element.parentNode.insertBefore(this._loadImgCopy, element);                               

        }

        

    },

    

    _removeLoadingImage : function()

    {

        if(this._loadImgCopy)

        {

            var element = $get(this._elementId);   

            element.parentNode.removeChild(this._loadImgCopy);

            this._loadImgCopy = null;

        }

    },

    

    _LoadImage : function()

    {    

        this._setLoadingImage();

        this.get_element().src = this._imageUrl;

    

    },


    _OnLoad : function()

    {                                                                                                                

        this._removeLoadingImage();

        this.autoAdjustImage();           

        

    },       

                

    

    autoAdjustImage : function()

    {

        var element = $get(this._elementId);

                

        element.removeAttribute('height');

        element.style.height = 'auto';        

        element.removeAttribute('width');

        element.style.width = 'auto';

        

        var imageBounds = Sys.UI.DomElement.getBounds(element);                                                           

                                                

        var imageDimensionRatio = imageBounds.height / imageBounds.width;               

        

        var containerDimensionRatio = this._containerHeight / this._containerWidth;    

        

        if(this._horizontalCentered)

            element.removeAttribute('hspace');

            

        if(this._verticalCentered)

            element.removeAttribute('vspace');        

        

        if(imageDimensionRatio > containerDimensionRatio)

        {   

        

            element.setAttribute('height', '100%');

            element.style.height = '100%';

            

            if(this._horizontalCentered)

            {            

                        

                var scaleRatio = this._containerHeight / imageBounds.height;

            

                var newWidth = imageBounds.width * scaleRatio;

            

                var leftAdjust = (this._containerWidth - newWidth) / 2;                                   

                        

                element.setAttribute('hspace',leftAdjust);

            }                                                                                               

            

        }    

        else

        {

                                                                                    

            element.setAttribute('width', '100%');

            element.style.width = '100%';  

            

            if(this._verticalCentered)

            {  

            

                var scaleRatio = this._containerWidth / imageBounds.width  ;

            

                var newHeight = imageBounds.height * scaleRatio;

            

                var topAdjust = (this._containerHeight - newHeight) / 2;

            

                element.setAttribute('vspace',topAdjust);

            }                            

            

        }  

    },

    

    add_onClickHandler : function(handler)

    {               

        this.remove_onClickHandler();

         

        this._onClick = handler;

        

        $addHandler($get(this._elementId),'click', this._onClick);        

    },

    

    remove_onClickHandler : function()

    {

        if(this._onClick)

        {            

            $removeHandler($get(this._elementId),'click', this._onClick);

            this._onClick = null;

        }

    },

    

    get_containerHeight : function()

    {

        return this._containerHeight;

    },

    

    set_containerHeight : function(value)

    {

        if(this._containerHeight != value)

        {

            this._containerHeight = value;

        }

    },

    

    get_containerWidth : function()

    {

        return this._containerWidth;

    },

    

    set_containerWidth : function(value)

    {

        if(this._containerWidth != value)

        {

            this._containerWidth = value;

        }

    },

    

    get_elementId : function()

    {

        return this._elementId;

    },

    

    set_elementId : function(value)

    {

        if(this._elementId != value)

        {

            this._elementId = value;

        }

    },

    

    get_imageUrl : function()

    {

        return this._imageUrl;

    },

    

    set_imageUrl : function(value)

    {

        if(this._imageUrl != value)

        {

            this._imageUrl = value;

            this.raisePropertyChanged('imageUrl');

        }

    },

    

    get_horizontalCentered : function()

    {

        return this._horizontalCentered;

    },

    

    set_horizontalCentered : function(value)

    {

        if(this._horizontalCentered != value)

        {

            this._horizontalCentered = value;

            this.raisePropertyChanged('horizontalCentered');

        }

        

    },

    

    get_verticalCentered : function()

    {

        return this._verticalCentered;

    },

    

    set_verticalCentered : function(value)

    {

        if(this._verticalCentered != value)

        {

            this._verticalCentered = value;

            this.raisePropertyChanged('verticalCentered');

        }

        

    },

    

    get_loadImg : function()

    {

        return this._loadImg;

    },

    

    set_loadImg : function(value)

    {

        if(this._loadImg != value)

        {

            this._loadImg = value;

            this.raisePropertyChanged('loadImg');

        }

        

    },

    

    get_loadImgWidth : function()

    {

       return this._loadImgWidth;

    },

    

    set_loadImgWidth : function(value)

    {

        if(this._loadImgWidth != value)

        {

            this._loadImgWidth = value;

            this.raisePropertyChanged('loadImgWidth');

        }

        

    },

        

    get_loadImgHeight : function()

    {

       return this._loadImgHeight;

    },

    

    set_loadImgHeight : function(value)

    {

        if(this._loadImgHeight != value)

        {

            this._loadImgHeight = value;

            this.raisePropertyChanged('loadImgHeight');

        }

        

    }

    


};


//注册类

Controls.myImage.registerClass('Controls.myImage',Sys.UI.Control);


if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();

<code>

© . All rights reserved.