示例#1
0
    public static void LoadTexture()
    {
        Bitmap bitmap=null;
        BitmapData bitmapData=null;

        string[] tx={"relojes.bmp","ford1.bmp","benz1.jpg","motor.bmp","acelera.bmp","papel1.jpg","piso.jpg","madera2.jpg","madera3.jpg","papel1.jpg","Focus.jpg","fordrunner.jpg","mbne.jpg","particle.bmp","benz.jpg"};
        Gl.glEnable(Gl.GL_TEXTURE_2D);
        Gl.glEnable(Gl.GL_DEPTH_TEST);
        //		Gl.gl.Gl.glEnable(Gl.gl.Gl.gl_BLEND);
        //		Gl.gl.Gl.glBlendFunc(Gl.gl.Gl.gl_SRC_ALPHA,Gl.gl.Gl.gl_ONE_MINUS_SRC_ALPHA);
        Rectangle rect;
        texture=new int[tx.Length];
        Gl.glGenTextures(tx.Length, texture);
        for(int i=0; i<tx.Length; i++)
        {
            bitmap = new Bitmap(Application.StartupPath + "\\" + "Textures\\"+tx[i]);
            rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            bitmapData =bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture[i]);
            Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, (int) Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR_EXT, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0);
        }

        Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT);
        Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT);
        Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
        Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
        Gl.glTexEnvf(Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_DECAL);

        Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0);

        bitmap.UnlockBits(bitmapData);
        bitmap.Dispose();
    }
示例#2
0
    public void Draw(Graphics2D graphics) {
        Fill f = GetFill();
        Dimension pg = Sheet.GetSlideShow().GetPageSize();
        Rectangle anchor = new Rectangle(0, 0, pg.width, pg.height);
        switch (f.GetFillType()) {
            case Fill.FILL_SOLID:
                Color color = f.GetForegroundColor();
                graphics.SetPaint(color);
                graphics.Fill(anchor);
                break;
            case Fill.FILL_PICTURE:
                PictureData data = f.GetPictureData();
                if (data is Bitmap) {
                    BufferedImage img = null;
                    try {
                        img = ImageIO.Read(new MemoryStream(data.Data));
                    } catch (Exception e) {
                        logger.log(POILogger.WARN, "ImageIO failed to create image. image.type: " + data.GetType());
                        return;
                    }
                    Image scaledImg = img.GetScaledInstance(anchor.width, anchor.height, Image.SCALE_SMOOTH);
                    graphics.DrawImage(scaledImg, anchor.x, anchor.y, null);

                }
                break;
            default:
                logger.log(POILogger.WARN, "unsuported fill type: " + f.GetFillType());
                break;
        }
    }
        public bool CheckHouseRegionOverlap(string owner, Rectangle regionArea)
        {
            for (int i = 0; i < TShock.Regions.Regions.Count; i++) {
            Region tsRegion = TShock.Regions.Regions[i];
            if (
              regionArea.Right < tsRegion.Area.Left || regionArea.X > tsRegion.Area.Right ||
              regionArea.Bottom < tsRegion.Area.Top || regionArea.Y > tsRegion.Area.Bottom
            )
              continue;

            string houseOwner;
            int houseIndex;
            if (!this.TryGetHouseRegionData(tsRegion.Name, out houseOwner, out houseIndex)) {
              if (this.Config.AllowTShockRegionOverlapping || tsRegion.Name.StartsWith("*"))
            continue;

              return true;
            }
            if (houseOwner == owner)
              continue;

            return true;
              }

              return false;
        }
 /// <summary>Draws the given rectangle.</summary>
 /// <param name="r">The rectangle to draw.</param>
 /// <param name="col">The color to draw the rectangle in.</param>
 /// <param name="bw">The border width to draw the rectangle with. (shadow to botom-right)</param>
 public static void DrawRectangle(Rectangle r, SpriteBatch spriteBatch, Color col, int bw = 2)
 {
     spriteBatch.Draw(pixel, new Rectangle(r.Left, r.Top, bw, r.Height), col); // Left
     spriteBatch.Draw(pixel, new Rectangle(r.Right, r.Top, bw, r.Height), col); // Right
     spriteBatch.Draw(pixel, new Rectangle(r.Left, r.Top, r.Width, bw), col); // Top
     spriteBatch.Draw(pixel, new Rectangle(r.Left, r.Bottom, r.Width, bw), col); // Bottom
 }
示例#5
0
        public override void Render(Sprite sprite)
        {
            Rectangle rect = new Rectangle(0, 0, 1280, 720);
            if (currentFrame >= frames.Length)
            {
                if (delay > 1.25f)
                {
                    sprite.Draw(frames[frames.Length - 1], rect, ColorValue.White);
                    ColorValue color = ColorValue.White;
                    color.A = (byte)(byte.MaxValue * (1 - MathEx.Saturate((delay - 1.25f) / 1.25f)));
                    sprite.Draw(blackBg, rect, color);
                }
                else
                {
                    ColorValue color = ColorValue.White;
                    color.A = (byte)(byte.MaxValue * MathEx.Saturate(delay / 1.25f));
                    sprite.Draw(blackBg, rect, color);
                }


                delay -= 0.04f;
            }
            else
            {
                sprite.Draw(frames[currentFrame], rect, ColorValue.White);
            }
        }
示例#6
0
        public FastEngine(string windowName, int width, int height, int fps)
        {
            // disabling HiDPI support
            var options = new ToolkitOptions
            {
                EnableHighResolution = false
            };
            OpenTK.Toolkit.Init(options);
            window = new GameWindow (width, height, OpenTK.Graphics.GraphicsMode.Default, windowName);

            // call it AFTER GameWindow initialization to avoid problems with Windows.Forms
            this.Initialize (windowName, width, height, fps);

            // create a new texture
            texture = GL.GenTexture ();
            // use the texure (as a 2d one)
            GL.BindTexture (TextureTarget.Texture2D, texture);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            this.textureRect = new Rectangle (0, 0, width, height);

            GL.Enable (EnableCap.Texture2D);

            window.Resize += this.Game_Resize;
            window.RenderFrame += this.Game_RenderFrame;

            // initialize OpenAL context (No ! do it lazily)
            // audioContext = new AudioContext ();
        }
示例#7
0
	public static void Main(string[] args)
	{	
		Graphics.DrawImageAbort imageCallback;
		Bitmap outbmp = new Bitmap (300, 300);				
		Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver24bits.bmp");
		Graphics dc = Graphics.FromImage (outbmp);        
		
		ImageAttributes imageAttr = new ImageAttributes();
		
		/* Simple image drawing */		
		dc.DrawImage(bmp, 0,0);				
				
		/* Drawing using points */
		PointF ulCorner = new PointF(150.0F, 0.0F);
		PointF urCorner = new PointF(350.0F, 0.0F);
		PointF llCorner = new PointF(200.0F, 150.0F);
		RectangleF srcRect = new Rectangle (0,0,100,100);		
		PointF[] destPara = {ulCorner, urCorner, llCorner};	
		imageCallback =  new Graphics.DrawImageAbort(DrawImageCallback);		
		dc.DrawImage (bmp, destPara, srcRect, GraphicsUnit.Pixel, imageAttr, imageCallback);
	
		/* Using rectangles */	
		RectangleF destRect = new Rectangle (10,200,100,100);
		RectangleF srcRect2 = new Rectangle (50,50,100,100);		
		dc.DrawImage (bmp, destRect, srcRect2, GraphicsUnit.Pixel);		
		
		/* Simple image drawing with with scaling*/		
		dc.DrawImage(bmp, 200,200, 75, 75);				
		
		outbmp.Save("drawimage.bmp", ImageFormat.Bmp);				
		
	}
示例#8
0
 public Item(string spriteSheet, Rectangle sourceRect, int value, Point position)
 {
     Sprite = TextureManager.Instance.LoadTexture(spriteSheet);
     Source = sourceRect;
     Value = value;
     Position = position;
 }
        protected override void Paint(Graphics g, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
            DataGridViewElementStates cellState, object value, object formattedValue,
            string errorText, DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            int progressVal = 0;
              if (value != null)
            progressVal = (int)value;

              float percentage = (progressVal / 100.0f);
            // Need to convert to float before division; otherwise C# returns int which is 0 for anything but 100%.
              Brush backColorBrush = new SolidBrush(cellStyle.BackColor);
              Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor);
              // Draws the cell grid
              base.Paint(g, clipBounds, cellBounds,
                 rowIndex, cellState, value, formattedValue, errorText,
                 cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground));
              if (percentage > 0.0)
              {
            // Draw the progress bar and the text
            g.FillRectangle(new SolidBrush(Color.FromArgb(163, 189, 242)), cellBounds.X + 2, cellBounds.Y + 2,
                        Convert.ToInt32((percentage * cellBounds.Width - 4)), cellBounds.Height - 4);
            g.DrawString(progressVal + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
              }
              else
              {
            // draw the text
            if (DataGridView.CurrentRow.Index == rowIndex)
              g.DrawString(progressVal + "%", cellStyle.Font, new SolidBrush(cellStyle.SelectionForeColor), cellBounds.X + 6,
                       cellBounds.Y + 2);
            else
              g.DrawString(progressVal + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
              }
        }
示例#10
0
        /// <inheritdoc/>
        protected override void OnApply(ImageBase source, ImageBase target, Rectangle targetRectangle, Rectangle sourceRectangle)
        {
            float radians = (float)ImageMaths.DegreesToRadians(this.Angle);
            double cosradians = Math.Cos(radians);
            double sinradians = Math.Sin(radians);

            float lumR = .213f;
            float lumG = .715f;
            float lumB = .072f;

            float oneMinusLumR = 1 - lumR;
            float oneMinusLumG = 1 - lumG;
            float oneMinusLumB = 1 - lumB;

            // The matrix is set up to preserve the luminance of the image.
            // See http://graficaobscura.com/matrix/index.html
            // Number are taken from https://msdn.microsoft.com/en-us/library/jj192162(v=vs.85).aspx
            Matrix4x4 matrix4X4 = new Matrix4x4()
            {
                M11 = (float)(lumR + (cosradians * oneMinusLumR) - (sinradians * lumR)),
                M12 = (float)(lumR - (cosradians * lumR) - (sinradians * 0.143)),
                M13 = (float)(lumR - (cosradians * lumR) - (sinradians * oneMinusLumR)),
                M21 = (float)(lumG - (cosradians * lumG) - (sinradians * lumG)),
                M22 = (float)(lumG + (cosradians * oneMinusLumG) + (sinradians * 0.140)),
                M23 = (float)(lumG - (cosradians * lumG) + (sinradians * lumG)),
                M31 = (float)(lumB - (cosradians * lumB) + (sinradians * oneMinusLumB)),
                M32 = (float)(lumB - (cosradians * lumB) - (sinradians * 0.283)),
                M33 = (float)(lumB + (cosradians * oneMinusLumB) + (sinradians * lumB))
            };

            this.matrix = matrix4X4;
        }
示例#11
0
 public RectangleImpl(Rectangle r)
 {
     minX = r.GetMinX();
     maxX = r.GetMaxX();
     minY = r.GetMinY();
     maxY = r.GetMaxY();
 }
示例#12
0
        public bool CollidesWith(IVector2D movement, Rectangle rectangle)
        {
            IVector2D envelopeOrigin = Origin.Add(movement);
            var envelope = new Rectangle(envelopeOrigin, Size);
            envelope = envelope.EnlargeRectangleRectangle(this);

            if (envelope.CollidesWith(rectangle))
            {
                float min = Size.X.Minimum(Size.Y) / 4.0f;
                float minimumMoveDistance = min.Maximum(Helper.Epsilon);

                if (movement.Length() < minimumMoveDistance)
                {
                    return true;
                }

                IVector2D halfMovement = movement.Divide(2.0f);

                envelope = new Rectangle(Origin.Add(halfMovement), Size);

                return CollidesWith(halfMovement, rectangle) ||
                       envelope.CollidesWith(halfMovement, rectangle);
            }

            return false;
        }
示例#13
0
文件: Table.cs 项目: hanwangkun/npoi
    /**
     * Create a new Table of the given number of rows and columns
     *
     * @param numrows the number of rows
     * @param numcols the number of columns
     */
    public Table(int numrows, int numcols) {
        base();

        if(numrows < 1) throw new ArgumentException("The number of rows must be greater than 1");
        if(numcols < 1) throw new ArgumentException("The number of columns must be greater than 1");

        int x=0, y=0, tblWidth=0, tblHeight=0;
        cells = new TableCell[numrows][numcols];
        for (int i = 0; i < cells.Length; i++) {
            x = 0;
            for (int j = 0; j < cells[i].Length; j++) {
                cells[i][j] = new TableCell(this);
                Rectangle anchor = new Rectangle(x, y, TableCell.DEFAULT_WIDTH, TableCell.DEFAULT_HEIGHT);
                cells[i][j].SetAnchor(anchor);
                x += TableCell.DEFAULT_WIDTH;
            }
            y += TableCell.DEFAULT_HEIGHT;
        }
        tblWidth = x;
        tblHeight = y;
        SetAnchor(new Rectangle(0, 0, tblWidth, tblHeight));

        EscherContainerRecord spCont = (EscherContainerRecord) GetSpContainer().GetChild(0);
        EscherOptRecord opt = new EscherOptRecord();
        opt.SetRecordId((short)0xF122);
        opt.AddEscherProperty(new EscherSimpleProperty((short)0x39F, 1));
        EscherArrayProperty p = new EscherArrayProperty((short)0x43A0, false, null);
        p.SetSizeOfElements(0x0004);
        p.SetNumberOfElementsInArray(numrows);
        p.SetNumberOfElementsInMemory(numrows);
        opt.AddEscherProperty(p);
        List<EscherRecord> lst = spCont.GetChildRecords();
        lst.Add(lst.Count-1, opt);
        spCont.SetChildRecords(lst);
    }
示例#14
0
        /// <inheritdoc/>
        protected override void Apply(ImageBase target, ImageBase source, Rectangle targetRectangle, Rectangle sourceRectangle, int startY, int endY)
        {
            float brightness = this.Value / 100f;
            int sourceY = sourceRectangle.Y;
            int sourceBottom = sourceRectangle.Bottom;
            int startX = sourceRectangle.X;
            int endX = sourceRectangle.Right;

            Parallel.For(
                startY,
                endY,
                y =>
                    {
                        if (y >= sourceY && y < sourceBottom)
                        {
                            for (int x = startX; x < endX; x++)
                            {
                                Color color = Color.Expand(source[x, y]);

                                Vector3 vector3 = color.ToVector3();
                                vector3 += new Vector3(brightness);

                                target[x, y] = Color.Compress(new Color(vector3, color.A));
                            }
                            this.OnRowProcessed();
                        }
                    });
        }
        public override void DrawText(char[] buffer, Rectangle logicalTextBox, int textAlignment)
        {


            var clipRect = System.Drawing.Rectangle.Intersect(logicalTextBox.ToRect(), currentClipRect);
            //1.
            clipRect.Offset(canvasOriginX, canvasOriginY);
            //2.
            win32MemDc.SetClipRect(clipRect.Left, clipRect.Top, clipRect.Width, clipRect.Height);
            //3.
            NativeTextWin32.TextOut(win32MemDc.DC, CanvasOrgX + logicalTextBox.X, CanvasOrgY + logicalTextBox.Y, buffer, buffer.Length);
            //4.
            win32MemDc.ClearClipRect();

            //ReleaseHdc();
            //IntPtr gxdc = gx.GetHdc();
            //MyWin32.SetViewportOrgEx(gxdc, CanvasOrgX, CanvasOrgY, IntPtr.Zero);
            //System.Drawing.Rectangle clipRect =
            //    System.Drawing.Rectangle.Intersect(logicalTextBox.ToRect(), currentClipRect);
            //clipRect.Offset(CanvasOrgX, CanvasOrgY);
            //MyWin32.SetRectRgn(hRgn, clipRect.X, clipRect.Y, clipRect.Right, clipRect.Bottom);
            //MyWin32.SelectClipRgn(gxdc, hRgn);
            //NativeTextWin32.TextOut(gxdc, logicalTextBox.X, logicalTextBox.Y, buffer, buffer.Length); 
            //MyWin32.SelectClipRgn(gxdc, IntPtr.Zero); 
            //MyWin32.SetViewportOrgEx(gxdc, -CanvasOrgX, -CanvasOrgY, IntPtr.Zero); 
            //gx.ReleaseHdc();

        }
示例#16
0
    public static Rectangle CreateRectangle(Brush brush)
    {
        Rectangle rt = new Rectangle();
        rt.Fill = brush;

        return rt;
    }
示例#17
0
        static void Main(string[] args)
        {
            // declare and initialize two int arrays with coordinates of 2 points
            int[] coords1 = { 2, 5 };
            int[] coords2 = { 4, 3 };

            // declare and initialize 2 points
            Point point1 = new Point(coords1);
            Point point2 = new Point(coords2);

            // declare and initialize an array with the 2 points
            Point[] points = { point1, point2 };

            // declare and initialize a rectangle
            Rectangle rectangle = new Rectangle(points);
            
            // show rectangle coordinates
            Console.WriteLine(rectangle);

            // show rectangle`s perimeter
            Console.WriteLine(rectangle.Perimeter());

            // show area of the circle around the rectangle
            Console.WriteLine(rectangle.Circle());
        }
示例#18
0
        public bool CollidesWith(IVector2D movement, Rectangle rectangle)
        {
            IVector2D halfMovement = movement.Divide(2.0f);
            float movementDistance = movement.Length();
            IVector2D envelopeCenter = Center.Add(halfMovement);
            float envelopeRadius = Radius + movementDistance / 2.0f;
            var envelope = new Circle(envelopeCenter, envelopeRadius);

            if (envelope.CollidesWith(rectangle))
            {
                float minimumMoveDistance = (Radius / 4.0f).Maximum(Helper.Epsilon);

                if (movementDistance < minimumMoveDistance)
                {
                    return true;
                }

                envelope = new Circle(envelope.Center, Radius);

                return CollidesWith(halfMovement, rectangle) ||
                       envelope.CollidesWith(halfMovement, rectangle);
            }

            return false;
        }
示例#19
0
        public CameraEvent(string type, bool bubbles=false, Rectangle data=null, bool cancelable=true )
            : base(type, bubbles, cancelable)
        {
            //super(type, bubbles, cancelable);

            _data = data;
        }
示例#20
0
 public static System.Drawing.RectangleF FromDesktopRect(Rectangle r)
 {
     r.Y = (float)desktopBounds.Height - r.Y - r.Height;
     if (desktopBounds.Y < 0)
         r.Y += (float)desktopBounds.Y;
     return new System.Drawing.RectangleF ((float)r.X, (float)r.Y, (float)r.Width, (float)r.Height);
 }
示例#21
0
文件: Util.cs 项目: dellis1972/xwt
 public static void SetWidgetBounds(this NSView v, Rectangle rect)
 {
     float y = (float)rect.Y;
     if (v.Superview != null)
         y = v.Superview.Frame.Height - y - (float)rect.Height;
     v.Frame = new System.Drawing.RectangleF ((float)rect.X, y, (float)rect.Width, (float)rect.Height);
 }
示例#22
0
        public void DrawGraphic(ref Hashtable graphicLibrary, int frameNumber, Point3D location, Size objSize, ref Bitmap image)
        {
            if (location.X >= 0 || location.Y >= 0 ||
                location.X + ((Bitmap)graphicLibrary[BaseImage]).Width >= 0 ||
                location.Y + ((Bitmap)graphicLibrary[BaseImage]).Height >= 0 &&
                location.X > NumberOfFrames)
                frameNumber -= NumberOfFrames;

            var gfx = Graphics.FromImage(image);

            var grab = FrameInitialOffset;
            if (Vertical)
            {
                grab.Y = FrameInitialOffset.Y + FrameSize.Height * (frameNumber - 1);
            }
            else
            {
                grab.X = FrameInitialOffset.X + FrameSize.Width * (frameNumber - 1);
            }

            var destRec = new Rectangle(location.X, location.Y, objSize.Width, objSize.Height);
            var srcRec = new Rectangle(grab, FrameSize);

            gfx.DrawImage(graphicLibrary[BaseImage] as Bitmap, destRec, srcRec, GraphicsUnit.Pixel);
        }
示例#23
0
        private Rectangle boxBlank ;    // 空き位置

        /// <summary>
        /// 初期化ボタン
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clickInit(object sender, EventArgs e)
        {
            var cols = new List<Color>()
            {
                Color.Red,
                Color.Navy,
                Color.Yellow,
                Color.Pink,
                Color.Purple,
            };
            var rnd = new Random();

            // キャンバスに Box を25個並べる
            boxes = new List<BoxViewEx>();
            for (int i = 0; i < 25; i++) {
                var box = new BoxViewEx();
                boxes.Add(box);
                canvas.Children.Add(box);
                int w = 60;
                int h = 60;

                int x = (i % 5) * (w + 10) + 30;
                int y = (i / 5) * (h + 10) + 30;

                var rect = new Rectangle(new Point(x, y), new Size(w, h));
                box.LayoutTo(rect);
                box.BackgroundColor = cols[ rnd.Next(cols.Count)];
                box.ManipulationDelta += Box_ManipulationDelta;
                box.ManipulationCompleted += Box_ManipulationCompleted;
                box.ManipulationStarted += Box_ManipulationStarted;
            }
        }
示例#24
0
    void OnPaint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;

          Rectangle r = new Rectangle(1, 1, castle.Width, castle.Height);
          g.DrawImage(castle, r);
    }
示例#25
0
    /// <summary>
    /// Checks whether or not the given ball is colliding with this paddle.
    /// </summary>
    /// <param name="b"></param>
    /// <returns></returns>
    public bool CollisionCheck(Ball b)
    {
        Rectangle recBall = new Rectangle((int)b.position.X - b.texture.Width / 2, (int)b.position.Y - b.texture.Height / 2, b.texture.Width, b.texture.Height);
        Rectangle recPaddle = new Rectangle((int)this.position.X - this.texture.Width / 2, (int)this.position.Y - this.texture.Height / 2, this.texture.Width, this.texture.Height);

        return !(Rectangle.Empty == Rectangle.Intersect(recBall, recPaddle));
    }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Button"/> class.
 /// </summary>
 /// <param name='bounds'>
 /// Bounds.
 /// </param>
 /// <param name='content'>
 /// Content.
 /// </param>
 /// <param name='style'>
 /// Style.
 /// </param>
 public Button(Rectangle bounds, GUIContent content, GUISkin skin)
     : this()
 {
     this.Bounds = bounds;
     this.Content = content;
     this.Skin = skin;
 }
示例#27
0
		protected override void OnSizeAllocated (double width, double height)
		{
			base.OnSizeAllocated (width, height);

			if (width != -1) {

				Device.BeginInvokeOnMainThread (() => {

					//Adjust height of pintile so it is equal to the width
					var tileLayout = new Rectangle (Bounds.X, Bounds.Y, Bounds.Width, width);
					this.Layout (tileLayout);

					this.ParentView.Layout (new Rectangle (ParentView.Bounds.X, ParentView.Bounds.Y, ParentView.Bounds.Width, width));

					//Ugly bug fix for iOS to get text centered vertically in label - needed in Xamarin.Forms 1.4.0.6341
					int yPositionLabel = 0;

					if (DeviceTypeHelper.IsIos) {
						if(Bounds.Height <= 65){
							yPositionLabel = 11;
						}
						else{
							yPositionLabel = 14;
						}
					}
					else if (DeviceTypeHelper.IsAndroid) {
						if(Bounds.Height > 55 && Bounds.Height < 70){
							yPositionLabel = 5;
						}
					}

					_labelPin.Layout (new Rectangle (_labelPin.X, yPositionLabel, Bounds.Width, Bounds.Height));
				});
			}
		}
示例#28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NPCSpawner"/> class.
        /// </summary>
        /// <param name="mapSpawnValues">The MapSpawnValues containing the values to use to create this NPCSpawner.</param>
        /// <param name="map">The Map instance to do the spawning on. The <see cref="MapID"/> of this Map must be equal to the
        /// <see cref="MapID"/> of the <paramref name="mapSpawnValues"/>.</param>
        /// <exception cref="ArgumentException">The <paramref name="map"/>'s <see cref="MapID"/> does not match the
        /// <paramref name="mapSpawnValues"/>'s <see cref="MapID"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="map" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="mapSpawnValues" /> is <c>null</c>.</exception>
        public NPCSpawner(IMapSpawnTable mapSpawnValues, Map map)
        {
            if (map == null)
                throw new ArgumentNullException("map");
            if (mapSpawnValues == null)
                throw new ArgumentNullException("mapSpawnValues");

            if (map.ID != mapSpawnValues.MapID)
                throw new ArgumentException("The map's MapID and mapSpawnValues's MapID do not match.", "map");

            _map = map;
            _characterTemplate = _characterTemplateManager[mapSpawnValues.CharacterTemplateID];
            _characterTemplateBody = BodyInfoManager.Instance.GetBody(_characterTemplate.TemplateTable.BodyID);
            _amount = mapSpawnValues.Amount;
            _area = new MapSpawnRect(mapSpawnValues).ToRectangle(map);
            _spawnDirection = mapSpawnValues.DirectionId;
            _respawn = mapSpawnValues.Respawn;

            if (_characterTemplate == null)
            {
                const string errmsg = "Failed to find the CharacterTemplate for CharacterTemplateID `{0}`.";
                var err = string.Format(errmsg, mapSpawnValues.CharacterTemplateID);
                if (log.IsFatalEnabled)
                    log.Fatal(err);
                Debug.Fail(err);
                throw new ArgumentException(err);
            }

            SpawnNPCs();
        }
示例#29
0
 public QuadPrefixTree(SpatialContext ctx, Rectangle bounds, int maxLevels)
     : base(ctx, maxLevels)
 {
     //not really sure how big this should be
     // side
     // number
     xmin = bounds.GetMinX();
     xmax = bounds.GetMaxX();
     ymin = bounds.GetMinY();
     ymax = bounds.GetMaxY();
     levelW = new double[maxLevels];
     levelH = new double[maxLevels];
     levelS = new int[maxLevels];
     levelN = new int[maxLevels];
     gridW = xmax - xmin;
     gridH = ymax - ymin;
     xmid = xmin + gridW / 2.0;
     ymid = ymin + gridH / 2.0;
     levelW[0] = gridW / 2.0;
     levelH[0] = gridH / 2.0;
     levelS[0] = 2;
     levelN[0] = 4;
     for (int i = 1; i < levelW.Length; i++)
     {
         levelW[i] = levelW[i - 1] / 2.0;
         levelH[i] = levelH[i - 1] / 2.0;
         levelS[i] = levelS[i - 1] * 2;
         levelN[i] = levelN[i - 1] * 4;
     }
 }
示例#30
0
        public static void initialize()
        {
            Vector2 pos = Screen.getXYfromCenter(-400, -120);
            backgroundRectangle = new Rectangle((int)pos.X, (int)pos.Y, 1000, 200);
            pos = Screen.getXYfromCenter(-520, -125);
            portraitRectangle = new Rectangle((int)pos.X, (int)pos.Y, 150, 150);

            string[] characterNames = { "Wish", "DarkWish", "OnionElder", "KingTomato", "Macedonia" };// Enum.GetNames(Type.GetType("MyGame.tDialogCharacter"));
            int numberOfCharacters = characterNames.Length;

            DialogEvent.dialogBackground = TextureManager.Instance.getTexture("GUI/menu/dialogBackground");
            DialogEvent.portraits = new Texture2D[numberOfCharacters];
            DialogEvent.portraits[(int)tDialogCharacter.Wish] = TextureManager.Instance.getTexture("GUI/portraits/portraitWish");
            DialogEvent.portraits[(int)tDialogCharacter.DarkWish] = TextureManager.Instance.getTexture("GUI/portraits/mrblack-89");
            DialogEvent.portraits[(int)tDialogCharacter.OnionElder] = TextureManager.Instance.getTexture("GUI/portraits/portraitOnionElder");
            DialogEvent.portraits[(int)tDialogCharacter.KingTomato] = TextureManager.Instance.getTexture("GUI/portraits/portraitKingTomato");
            DialogEvent.portraits[(int)tDialogCharacter.Macedonia] = TextureManager.Instance.getTexture("GUI/portraits/portraitMacedonia");

            DialogEvent.characterAudios = new string[numberOfCharacters,N_DIALOGS];
            for (int i = 0; i < characterNames.Length; ++i)
            {
                for (int j = 0; j < N_DIALOGS; ++j)
                {
                    characterAudios[i,j] = "dialog" + characterNames[i] + (j+1).ToString();
                }
            }
            dialogTimes = new float[numberOfCharacters];
            dialogTimes[(int)tDialogCharacter.Wish] = 0.8f;
            dialogTimes[(int)tDialogCharacter.DarkWish] = 0.7f;
            dialogTimes[(int)tDialogCharacter.OnionElder] = 1.0f;
            dialogTimes[(int)tDialogCharacter.KingTomato] = 0.5f;
            dialogTimes[(int)tDialogCharacter.Macedonia] = 0.5f;
        }
示例#31
0
        protected override void OnPaint(PaintEventArgs e)
        {
            using (SolidBrush b = new SolidBrush(BackColor))
            {
                e.Graphics.FillRectangle(b, ClientRectangle);
            }

            RectangleF lr       = ClientRectangleF;
            Pen        framepen = new Pen(m_frameColor, 1);

            Util.DrawFrame(e.Graphics, lr, 6, m_frameColor);
            if (Text.Length > 0)
            {
                StringFormat format    = new StringFormat();
                string       alignment = TextAlign.ToString();

                if (((int)TextAlign & (int)(ContentAlignment.BottomLeft | ContentAlignment.MiddleLeft | ContentAlignment.TopLeft)) != 0)
                {
                    format.Alignment = StringAlignment.Near;
                }

                if (((int)TextAlign & (int)(ContentAlignment.BottomCenter | ContentAlignment.MiddleCenter | ContentAlignment.TopCenter)) != 0)
                {
                    format.Alignment = StringAlignment.Center;
                }

                if (((int)TextAlign & (int)(ContentAlignment.BottomRight | ContentAlignment.MiddleRight | ContentAlignment.TopRight)) != 0)
                {
                    format.Alignment = StringAlignment.Far;
                }

                if (((int)TextAlign & (int)(ContentAlignment.BottomLeft | ContentAlignment.BottomCenter | ContentAlignment.BottomRight)) != 0)
                {
                    format.LineAlignment = StringAlignment.Far;
                }

                if (((int)TextAlign & (int)(ContentAlignment.MiddleLeft | ContentAlignment.MiddleCenter | ContentAlignment.MiddleRight)) != 0)
                {
                    format.LineAlignment = StringAlignment.Center;
                }

                if (((int)TextAlign & (int)(ContentAlignment.TopLeft | ContentAlignment.TopCenter | ContentAlignment.TopRight)) != 0)
                {
                    format.LineAlignment = StringAlignment.Near;
                }

                Rectangle r = ClientRectangle;
                r.X      += Padding.Left;
                r.Y      += Padding.Top;
                r.Width  -= Padding.Right;
                r.Height -= Padding.Bottom;

                using (SolidBrush b = new SolidBrush(ForeColor))
                {
                    if (TextAngle == 0)
                    {
                        e.Graphics.DrawString(Text, Font, b, r, format);
                    }
                    else
                    {
                        PointF center = Util.Center(ClientRectangle);
                        switch (RotatePointAlignment)
                        {
                        case ContentAlignment.TopLeft:
                            center.X = r.Left;
                            center.Y = r.Top;
                            break;

                        case ContentAlignment.TopCenter:
                            center.Y = r.Top;
                            break;

                        case ContentAlignment.TopRight:
                            center.X = r.Right;
                            center.Y = r.Top;
                            break;

                        case ContentAlignment.MiddleLeft:
                            center.X = r.Left;
                            break;

                        case ContentAlignment.MiddleCenter:
                            break;

                        case ContentAlignment.MiddleRight:
                            center.X = r.Right;
                            break;

                        case ContentAlignment.BottomLeft:
                            center.X = r.Left;
                            center.Y = r.Bottom;
                            break;

                        case ContentAlignment.BottomCenter:
                            center.Y = r.Bottom;
                            break;

                        case ContentAlignment.BottomRight:
                            center.X = r.Right;
                            center.Y = r.Bottom;
                            break;
                        }
                        center.X += Padding.Left;
                        center.Y += Padding.Top;
                        center.X -= Padding.Right;
                        center.Y -= Padding.Bottom;

                        e.Graphics.TranslateTransform(center.X, center.Y);
                        e.Graphics.RotateTransform(TextAngle);

                        e.Graphics.DrawString(Text, Font, b, new PointF(0, 0), format);
                        e.Graphics.ResetTransform();
                    }
                }
            }
            RaisePaintEvent(this, e);
        }
示例#32
0
 /// <inheritdoc cref="RoundedRect(Nvg, Rectangle{float}, float)"/>
 public static void RoundedRect(this Nvg nvg, float x, float y, float w, float h, float r)
 => RoundedRect(nvg, Rectangle.FromLTRB(x, y, x + w, y + h), r);
示例#33
0
 /// <summary>
 /// Creates a new rounded rectangle shaped sub-path.
 /// </summary>
 public static void RoundedRect(this Nvg nvg, Rectangle <float> rect, float r)
 {
     RoundedRectVarying(nvg, rect, r, r, r, r);
 }
示例#34
0
 /// <inheritdoc cref="Rect(Nvg, Rectangle{float})"/>
 public static void Rect(this Nvg nvg, float x, float y, float w, float h)
 => Rect(nvg, Rectangle.FromLTRB(x, y, x + w, y + h));
示例#35
0
 public override void MeleeEffects(Player player, Rectangle hitbox)
 {
     int dust = Dust.NewDust(new Vector2(hitbox.X, hitbox.Y), hitbox.Width, hitbox.Height, 59);
 }
示例#36
0
 public Rectangle AddCamera(Rectangle drawRect)
 {
     return(new Rectangle(drawRect.X + X, drawRect.Y + Y, drawRect.Width, drawRect.Height));
 }
示例#37
0
        /// <summary>
        /// Pattern Maching으로 Mark의 위치 확인
        /// </summary>
        /// <param name="iCamNo": Camera Number></param>
        /// <param name="iModelNo": Model Mark Number></param>
        /// <param name="SearchArea": Search Area Rectangle></param>
        /// <param name="ModelArea": Model Area Rectangle></param>
        /// <param name="ReferencePoint": Reference Point></param>
        /// <returns></returns>
        public int RegisterPatternMark(int iCamNo,
                                       string strModel,
                                       int iTypeNo,
                                       ref Rectangle SearchArea,
                                       ref Rectangle ModelArea,
                                       ref Point ReferencePoint)
        {
#if SIMULATION_VISION
                return SUCCESS;
#endif
            // Vision System이 초기화 된지를 확인함
            if (m_bSystemInit == false) return GenerateErrorCode(ERR_VISION_SYSTEM_FAIL);

            // 모델 갯수 보다 큰 경우 Err
            if (iTypeNo > DEF_USE_SEARCH_MARK_NO) return GenerateErrorCode(ERR_VISION_PATTERN_NUM_OVER);
            // Search Size 확인 
            if (SearchArea.Width <= DEF_SEARCH_MIN_WIDTH ||
               SearchArea.Height <= DEF_SEARCH_MIN_HEIGHT ||
               SearchArea.Width > m_RefComp.Camera[iCamNo].m_CamPixelSize.Width ||
               SearchArea.Height > m_RefComp.Camera[iCamNo].m_CamPixelSize.Height)
            {
                GenerateErrorCode(ERR_VISION_SEARCH_SIZE_OVER);
            }

            // 기존의 Mark 모델 Data를 연결함 (주소값으로 연결됨).
            CVisionPatternData pSData = m_RefComp.Camera[iCamNo].GetSearchData(iTypeNo);

            // 등록할 Mark의 Size 및 위치를 설정함.
            pSData.m_rectModel = ModelArea;
            pSData.m_rectSearch = SearchArea;
            pSData.m_pointReference = ReferencePoint;            

            // 기존에 등록된 모델이 있을 경우 삭제한다.
            if(pSData.m_milModel != MIL.M_NULL)
            {
                MIL.MpatFree(pSData.m_milModel);
                pSData.m_milModel = MIL.M_NULL;
                pSData.m_bIsModel = false;
            }

            // 설정한 Data로 Mark 모델을 등록한다.
            if(m_RefComp.System.RegisterMarkModel(iCamNo, ref pSData)==true)
            {
                pSData.m_bIsModel = true;
                // Model Register Grab Image Save
                string strPath = DEF_PATTERN_FILE;
                string strName = strModel + $"_Cam_{iCamNo}_Type_{iTypeNo}.bmp";
                // Image Save
                SaveModelImage(iCamNo, strPath, strName);

                // Image Path & Name apply
                pSData.m_strFilePath = strPath;
                pSData.m_strFileName = strName;
                
                return SUCCESS;
            }
            else
            {
                pSData.m_bIsModel = false;
                return GenerateErrorCode(ERR_VISION_PATTERN_REG_FAIL);
            }                 
        }
示例#38
0
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">保存路径</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原图与模版比例相等,直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原图与模版比例不等,裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0);//原图裁剪定位
                    Rectangle toR = new Rectangle(0, 0, 0, 0);//目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X = 0;
                        fromR.Y = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y = 0;
                        fromR.Width = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //关键质量控制
                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo ici = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存缩略图
                    templateImage.Save(fileSaveUrl, ici, ep);
                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //释放资源
            initImage.Dispose();
        }
示例#39
0
        public ActionResult AccountLedger(String StartDate, String EndDate, Int32 CompanyId, Int32 BranchId, Int32 AccountId)
        {
            // ============
            // PDF Settings
            // ============
            MemoryStream workStream = new MemoryStream();
            Rectangle rectangle = new Rectangle(PageSize.A3);
            Document document = new Document(rectangle, 72, 72, 72, 72);
            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // ===================
            // Fonts Customization
            // ===================
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11 = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10 = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.Company).FirstOrDefault();
            var address = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.Address).FirstOrDefault();
            var contactNo = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.ContactNumber).FirstOrDefault();
            var branch = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);
            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold)) { Border = 0 });
            headerPage.AddCell(new PdfPCell(new Phrase("Account Ledger", fontArial17Bold)) { Border = 0, HorizontalAlignment = 2 });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11)) { Border = 0, PaddingTop = 5f });
            headerPage.AddCell(new PdfPCell(new Phrase("Date From " + Convert.ToDateTime(StartDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " to " + Convert.ToDateTime(EndDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11)) { Border = 0, PaddingTop = 5f, HorizontalAlignment = 2 });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11)) { Border = 0, PaddingTop = 5f });
            headerPage.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11)) { Border = 0, PaddingTop = 5f, HorizontalAlignment = 2 });
            document.Add(headerPage);
            document.Add(line);

            // ========
            // Get Data
            // ========
            var accounts = from d in db.MstAccounts
                           where d.Id == AccountId
                           select d;

            if (accounts.Any())
            {
                // ============
                // Branch Title
                // ============
                PdfPTable branchTitle = new PdfPTable(1);
                float[] widthCellsBranchTitle = new float[] { 100f };
                branchTitle.SetWidths(widthCellsBranchTitle);
                branchTitle.WidthPercentage = 100;
                PdfPCell branchHeaderColspan = (new PdfPCell(new Phrase(branch, fontArial12Bold)) { Border = 0, HorizontalAlignment = 0, PaddingTop = 10f });
                branchTitle.AddCell(branchHeaderColspan);
                document.Add(branchTitle);

                // =============
                // Account Title 
                // =============
                PdfPTable itemTitle = new PdfPTable(1);
                float[] widthCellsItemTitle = new float[] { 100f };
                itemTitle.SetWidths(widthCellsItemTitle);
                itemTitle.WidthPercentage = 100;
                itemTitle.AddCell(new PdfPCell(new Phrase(accounts.FirstOrDefault().AccountCode + " - " + accounts.FirstOrDefault().Account, fontArial12Bold)) { Border = 0, HorizontalAlignment = 0, PaddingBottom = 14f });
                document.Add(itemTitle);

                var journals = from d in db.TrnJournals
                               where d.JournalDate >= Convert.ToDateTime(StartDate)
                               && d.JournalDate <= Convert.ToDateTime(EndDate)
                               && d.MstBranch.CompanyId == CompanyId
                               && d.BranchId == Convert.ToInt32(BranchId)
                               && d.AccountId == AccountId
                               select new
                               {
                                   JournalDate = d.JournalDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture),
                                   ManualNo = d.ORId != null ? d.TrnCollection.ManualORNumber :
                                              d.CVId != null ? d.TrnDisbursement.ManualCVNumber :
                                              d.JVId != null ? d.TrnJournalVoucher.ManualJVNumber :
                                              d.RRId != null ? d.TrnReceivingReceipt.ManualRRNumber :
                                              d.SIId != null ? d.TrnSalesInvoice.ManualSINumber :
                                              d.INId != null ? d.TrnStockIn.ManualINNumber :
                                              d.OTId != null ? d.TrnStockOut.ManualOTNumber :
                                              d.STId != null ? d.TrnStockTransfer.ManualSTNumber : " ",
                                   DocumentReference = d.DocumentReference,
                                   Article = d.MstArticle.Article,
                                   Particulars = d.Particulars,
                                   DebitAmount = d.DebitAmount,
                                   CreditAmount = d.CreditAmount
                               };

                if (journals.Any())
                {
                    // ====
                    // Data
                    // ====
                    PdfPTable tableData = new PdfPTable(8);
                    PdfPCell Cell = new PdfPCell();
                    float[] widthCellsTableData = new float[] { 65f, 125f, 125f, 130f, 150f, 100f, 100f, 100f };
                    tableData.SetWidths(widthCellsTableData);
                    tableData.WidthPercentage = 100;
                    tableData.AddCell(new PdfPCell(new Phrase("Date", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Manual No", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Doc. Reference", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Article", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Particulars", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Debit", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Credit", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });
                    tableData.AddCell(new PdfPCell(new Phrase("Balance", fontArial11Bold)) { HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY });

                    Decimal totalDebitAmount = 0;
                    Decimal totalCreditAmount = 0;
                    Decimal totalBalance = 0;

                    foreach (var journal in journals)
                    {
                        Decimal balance = journal.DebitAmount - journal.CreditAmount;

                        tableData.AddCell(new PdfPCell(new Phrase(journal.JournalDate, fontArial10)) { HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.ManualNo, fontArial10)) { HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.DocumentReference, fontArial10)) { HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.Article, fontArial10)) { HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.Particulars, fontArial10)) { HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.DebitAmount.ToString("#,##0.00"), fontArial10)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(journal.CreditAmount.ToString("#,##0.00"), fontArial10)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                        tableData.AddCell(new PdfPCell(new Phrase(balance.ToString("#,##0.00"), fontArial10)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });

                        totalDebitAmount += journal.DebitAmount;
                        totalCreditAmount += journal.CreditAmount;
                        totalBalance += journal.DebitAmount - journal.CreditAmount;
                    }

                    tableData.AddCell(new PdfPCell(new Phrase("Total", fontArial10Bold)) { Colspan = 5, HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                    tableData.AddCell(new PdfPCell(new Phrase(totalDebitAmount.ToString("#,##0.00"), fontArial10Bold)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                    tableData.AddCell(new PdfPCell(new Phrase(totalCreditAmount.ToString("#,##0.00"), fontArial10Bold)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                    tableData.AddCell(new PdfPCell(new Phrase(totalBalance.ToString("#,##0.00"), fontArial10Bold)) { HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f });
                    document.Add(tableData);
                }
            }

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return new FileStreamResult(workStream, "application/pdf");
        }
示例#40
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);
            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高
                int initWidth = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (System.Drawing.Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
            }
        }
示例#41
0
        private void UpdateWindowRegion_EmptyDocumentArea()
        {
            Rectangle rect = DocumentWindowBounds;

            SetRegion(new Rectangle[] { rect });
        }
示例#42
0
 private void DoDrawGrip(Graphics gr, Rectangle drawRect, Resco.Controls.ScrollBar.ScrollBar.ScrollBarOrientation orientation)
 {
     if (this._gripStyle != ScrollBarThumbGripStyle.None)
     {
         if (this._gripStyle == ScrollBarThumbGripStyle.Image)
         {
             if (this._gripImage != null)
             {
                 Rectangle destRect = new Rectangle(drawRect.Left + ((drawRect.Width - this._gripImage.Width) / 2), drawRect.Top + ((drawRect.Height - this._gripImage.Height) / 2), this._gripImage.Width, this._gripImage.Height);
                 gr.DrawImage(this._gripImage, destRect, 0, 0, this._gripImage.Width, this._gripImage.Height, GraphicsUnit.Pixel, this._gripImageAttributes);
             }
         }
         else if (this._gripLines > 0)
         {
             drawRect.Inflate(-1, -1);
             if ((drawRect.Width > 0) && (drawRect.Height > 0))
             {
                 int width = (this._gripLines * 2) - 1;
                 if (this._gripStyle == ScrollBarThumbGripStyle.Lines)
                 {
                     int left = drawRect.Left;
                     int top = drawRect.Top;
                     int num4 = 0;
                     int num5 = 0;
                     int num6 = 0;
                     int num7 = 0;
                     if (orientation == Resco.Controls.ScrollBar.ScrollBar.ScrollBarOrientation.Horizontal)
                     {
                         if (width < drawRect.Width)
                         {
                             left += (drawRect.Width - width) / 2;
                         }
                         else
                         {
                             width = drawRect.Width;
                         }
                         num4 = 2;
                         num7 = drawRect.Height - 1;
                     }
                     else
                     {
                         if (width < drawRect.Height)
                         {
                             top += (drawRect.Height - width) / 2;
                         }
                         else
                         {
                             width = drawRect.Height;
                         }
                         num5 = 2;
                         num6 = drawRect.Width - 1;
                     }
                     Pen pen = Resco.Controls.ScrollBar.ScrollBar.GetPen(this._gripColor);
                     for (int i = 0; i < width; i += 2)
                     {
                         gr.DrawLine(pen, left, top, left + num6, top + num7);
                         left += num4;
                         top += num5;
                     }
                 }
                 else if (this._gripStyle == ScrollBarThumbGripStyle.Dots)
                 {
                     int num9 = 0;
                     int height = 0;
                     int num12 = drawRect.Left;
                     int y = drawRect.Top;
                     if (orientation == Resco.Controls.ScrollBar.ScrollBar.ScrollBarOrientation.Horizontal)
                     {
                         if (width < drawRect.Width)
                         {
                             num12 += (drawRect.Width - width) / 2;
                         }
                         else
                         {
                             width = drawRect.Width;
                         }
                         num9 = width;
                         height = drawRect.Height;
                     }
                     else
                     {
                         if (width < drawRect.Height)
                         {
                             y += (drawRect.Height - width) / 2;
                         }
                         else
                         {
                             width = drawRect.Height;
                         }
                         num9 = drawRect.Width;
                         height = width;
                     }
                     for (int j = 0; j < height; j += 2)
                     {
                         int x = num12;
                         for (int k = 0; k < num9; k += 2)
                         {
                             Resco.Controls.ScrollBar.ScrollBar.DrawPixel(gr, this._gripColor, x, y);
                             x += 2;
                         }
                         y += 2;
                     }
                 }
             }
         }
     }
 }
示例#43
0
        private IEnumerable <Rectangle> IdentifyFacesFromSkinMask(DataRectangle <bool> skinMask)
        {
            if (skinMask == null)
            {
                throw new ArgumentNullException(nameof(skinMask));
            }

            // Identify potential objects from positive image (build a list of all skin points, take the first one and flood fill from it - recording the results as one object
            // and remove all points from the list, then do the same for the next skin point until there are none left)
            var skinPoints = new HashSet <Point>(
                skinMask.Enumerate((point, isMasked) => isMasked).Select(point => point.Item1)
                );
            var scale       = _config.CalculateScale(skinMask.Width, skinMask.Height);
            var skinObjects = new List <Point[]>();

            while (skinPoints.Any())
            {
                var currentPoint   = skinPoints.First();
                var pointsInObject = TryToGetPointsInObject(skinMask, currentPoint, new Rectangle(0, 0, skinMask.Width, skinMask.Height)).ToArray();
                foreach (var point in pointsInObject)
                {
                    skinPoints.Remove(point);
                }
                skinObjects.Add(pointsInObject);
            }
            skinObjects = skinObjects.Where(skinObject => skinObject.Length >= (64 * scale)).ToList();             // Ignore any very small regions

            if (_config.SaveProgressImages)
            {
                var skinMaskPreviewImage     = new Bitmap(skinMask.Width, skinMask.Height);
                var skinObjectPreviewColours = new[] { new RGB(255, 0, 0), new RGB(0, 255, 0), new RGB(0, 0, 255), new RGB(128, 128, 0), new RGB(0, 128, 128), new RGB(128, 0, 128) };
                var allSkinObjectPoints      = skinObjects.Select((o, i) => new { Points = new HashSet <Point>(o), Colour = skinObjectPreviewColours[i % skinObjectPreviewColours.Length] }).ToArray();
                skinMaskPreviewImage.SetRGB(
                    skinMask.Transform((isSkin, point) =>
                {
                    var firstObject = allSkinObjectPoints.FirstOrDefault(o => o.Points.Contains(point));
                    return((firstObject == null) ? new RGB(0, 0, 0) : firstObject.Colour);
                })
                    );
                skinMaskPreviewImage.Save("SkinObjects.png");
            }

            // Look for any fully enclosed holes in each skin object (do this by flood filling from negative points and ignoring any where the fill gets to the edges of object)
            var boundsForSkinObjects = new List <Rectangle>();

            foreach (var skinObject in skinObjects)
            {
                var xValues                = skinObject.Select(p => p.X).ToArray();
                var yValues                = skinObject.Select(p => p.Y).ToArray();
                var left                   = xValues.Min();
                var top                    = yValues.Min();
                var skinObjectBounds       = new Rectangle(left, top, width: (xValues.Max() - left) + 1, height: (yValues.Max() - top) + 1);
                var negativePointsInObject = new HashSet <Point>(
                    skinMask.Enumerate((point, isMasked) => !isMasked && skinObjectBounds.Contains(point)).Select(point => point.Item1)
                    );
                while (negativePointsInObject.Any())
                {
                    var currentPoint = negativePointsInObject.First();
                    var pointsInFilledNegativeSpace = TryToGetPointsInObject(skinMask, currentPoint, skinObjectBounds).ToArray();
                    foreach (var point in pointsInFilledNegativeSpace)
                    {
                        negativePointsInObject.Remove(point);
                    }

                    if (pointsInFilledNegativeSpace.Any(p => (p.X == skinObjectBounds.Left) || (p.X == (skinObjectBounds.Right - 1)) || (p.Y == skinObjectBounds.Top) || (p.Y == (skinObjectBounds.Bottom - 1))))
                    {
                        continue;                         // Ignore any negative regions that are not fully enclosed within the skin mask
                    }
                    if (pointsInFilledNegativeSpace.Length <= scale)
                    {
                        continue;                               // Ignore any very small regions (likely anomalies)
                    }
                    boundsForSkinObjects.Add(skinObjectBounds); // Found a non-negligible fully-enclosed hole
                    break;
                }
            }
            return(boundsForSkinObjects);
        }
示例#44
0
        private void Form3_Load(object sender, EventArgs e)
        {
            Rectangle workingArea = Screen.GetWorkingArea(this);

            this.Location = new Point(workingArea.Right - Size.Width, workingArea.Bottom - Size.Height);
        }
示例#45
0
 /// <summary>
 /// Draws the unit (unit type icon) at the specified rectangle.  Use this method to scale the icon.
 /// </summary>
 /// <param name="_dest">Rectangle structure containing pixel x,y destination and width/height.</param>
 public void Draw(Rectangle _dest)
 {
     UnitType.SpriteBatch.Draw(UnitType.SpriteSheet, _dest,
                               new Rectangle(this.SpritesheetX, this.SpritesheetY, UnitType.ImageWidth, UnitType.ImageHeight), Color.White);
 }
示例#46
0
        // Based on code from https://simpledevcode.wordpress.com/2015/12/29/flood-fill-algorithm-using-c-net/
        private static IEnumerable <Point> TryToGetPointsInObject(DataRectangle <bool> mask, Point startAt, Rectangle limitTo)
        {
            if (mask == null)
            {
                throw new ArgumentNullException(nameof(mask));
            }
            if ((limitTo.Left < 0) || (limitTo.Right > mask.Width) || (limitTo.Top < 0) || (limitTo.Bottom > mask.Height))
            {
                throw new ArgumentOutOfRangeException(nameof(limitTo));
            }
            if ((startAt.X < limitTo.Left) || (startAt.X > limitTo.Right) || (startAt.Y < limitTo.Top) || (startAt.Y > limitTo.Bottom))
            {
                throw new ArgumentOutOfRangeException(nameof(startAt));
            }

            var valueAtOriginPoint = mask[startAt.X, startAt.Y];

            var pixels = new Stack <Point>();

            pixels.Push(startAt);

            var filledPixels = new HashSet <Point>();

            while (pixels.Count > 0)
            {
                var currentPoint = pixels.Pop();
                if ((currentPoint.X < limitTo.Left) || (currentPoint.X >= limitTo.Right) || (currentPoint.Y < limitTo.Top) || (currentPoint.Y >= limitTo.Bottom))                 // make sure we stay within bounds
                {
                    continue;
                }

                if ((mask[currentPoint.X, currentPoint.Y] == valueAtOriginPoint) && !filledPixels.Contains(currentPoint))
                {
                    filledPixels.Add(new Point(currentPoint.X, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X - 1, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X + 1, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X, currentPoint.Y - 1));
                    pixels.Push(new Point(currentPoint.X, currentPoint.Y + 1));
                }
            }
            return(filledPixels);
        }
示例#47
0
 void mEntities_OnClear(object sender, EventArgs e)
 {
     mRectangle = Rectangle.Empty;
 }
 public BasicAnimatedSprite(Rectangle pos, double timePerFrame, Color color) : base(pos, color)
 {
     spriteSheet = false;
     this.timePerFrame = timePerFrame;
     animationExecutions = 0;
 }
        /// <inheritdoc/>
        public IImageProcessingContext<TPixel> ApplyProcessor(IImageProcessor<TPixel> processor, Rectangle rectangle)
        {
            if (!this.mutate && this.destination is null)
            {
                // This will only work if the first processor applied is the cloning one thus
                // realistically for this optimization to work the resize must the first processor
                // applied any only up processors will take the double data path.
                if (processor is ICloningImageProcessor<TPixel> cloningImageProcessor)
                {
                    this.destination = cloningImageProcessor.CloneAndApply(this.source, rectangle);
                    return this;
                }

                this.destination = this.source.Clone();
            }

            processor.Apply(this.destination, rectangle);
            return this;
        }
 public TextureRegion2D(string name, Texture2D texture, Rectangle region, Vector2 originNormalized = default(Vector2))
     : this(name, texture, region.X, region.Y, region.Width, region.Height, originNormalized)
 {
 }
示例#51
0
 public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin,
     float scale)
 {
     if (Main.netMode == NetmodeID.Server || LocalTexture == null) 
         return false;
     if (Main.itemTexture[item.type] == null) 
         Main.itemTexture[item.type] = LocalTexture;
     float s = scale * Main.itemTexture[item.type].Height / LocalTexture.Height;
     Draw(spriteBatch, position, drawColor, 0f, s);
     return false;
 }
示例#52
0
 public virtual UIElement WithSourceRectangle(Rectangle sourceRectangle)
 {
     SourceRectangle = sourceRectangle;
     return(this);
 }
示例#53
0
        public Vector2 Draw(SpriteBatch sb, Rectangle dest, ExtensionInfo info)
        {
            this.ActiveInfo = info;
            if (!this.HasInitializedSteamCallbacks)
            {
                this.InitSteamCallbacks();
            }
            this.Update();
            Vector2 vector2 = new Vector2((float)dest.X, (float)dest.Y);
            bool    flag1   = info.WorkshopPublishID != "NONE";

            this.currentStatusMessage = flag1 ? "Ready to push Updates" : "Ready to create in steam";
            if (!flag1 && string.IsNullOrWhiteSpace(this.currentBodyMessage))
            {
                this.currentBodyMessage = "By submitting this item, you agree to the workshop terms of service\nhttp://steamcommunity.com/sharedfiles/workshoplegalagreement";
            }
            Vector2 pos1 = new Vector2(vector2.X + (float)(dest.Width / 2), vector2.Y);

            TextItem.doFontLabel(pos1, this.currentStatusMessage, GuiData.font, new Color?(Color.Gray), (float)dest.Width / 2f, 30f, false);
            pos1.Y += 30f;
            TextItem.doFontLabel(pos1, this.currentTitleMessage, GuiData.font, new Color?(Color.White), (float)dest.Width / 2f, 30f, false);
            pos1.Y += 30f;
            Vector2 pos2 = pos1;

            if (this.showLoadingSpinner)
            {
                pos1.X          += 16f;
                this.spinnerRot += 0.1f;
                Rectangle destinationRectangle = new Rectangle((int)pos1.X, (int)pos1.Y + 20, 40, 40);
                sb.Draw(this.spinnerTex, destinationRectangle, new Rectangle?(), Color.White, this.spinnerRot, this.spinnerTex.GetCentreOrigin(), SpriteEffects.None, 0.5f);
                pos2.X += 45f;
            }
            if (this.isInUpload)
            {
                Rectangle rectangle          = new Rectangle((int)pos2.X, (int)pos2.Y + 6, dest.Width / 2, 20);
                ulong     punBytesProcessed  = 0;
                ulong     punBytesTotal      = 1;
                int       itemUpdateProgress = (int)SteamUGC.GetItemUpdateProgress(this.updateHandle, out punBytesProcessed, out punBytesTotal);
                double    val1 = (double)punBytesProcessed / (double)punBytesTotal;
                if ((long)punBytesTotal == 0L)
                {
                    val1 = 0.0;
                }
                sb.Draw(Utils.white, Utils.InsetRectangle(rectangle, -1), Utils.AddativeWhite * 0.7f);
                sb.Draw(Utils.white, rectangle, Utils.VeryDarkGray);
                rectangle.Width = (int)((double)rectangle.Width * val1);
                sb.Draw(Utils.white, rectangle, Color.LightBlue);
                pos2.Y += 31f;
                if (punBytesTotal > 0UL)
                {
                    string format = "{0}% - {1}mb of {2}mb Transfered";
                    string str1   = (val1 * 100.0).ToString("00.00");
                    ulong  num    = punBytesProcessed / 1000000UL;
                    string str2   = num.ToString("0.00");
                    num = punBytesTotal / 1000000UL;
                    string str3  = num.ToString("0.00");
                    string text1 = string.Format(format, (object)str1, (object)str2, (object)str3);
                    Utils.DrawStringMonospace(sb, text1, GuiData.smallfont, pos2, Color.White, 9f);
                    pos2.Y += 20f;
                    TimeSpan time  = DateTime.Now - this.transferStarted;
                    string   text2 = string.Format("ETA: {0} // Elapsed : {1}", (object)this.getTimespanDisplayString(TimeSpan.FromSeconds(time.TotalSeconds / Math.Max(val1, 0.01))), (object)this.getTimespanDisplayString(time));
                    Utils.DrawStringMonospace(sb, text2, GuiData.smallfont, pos2, Color.White, 9f);
                    pos2.Y += 25f;
                }
            }
            TextItem.doFontLabel(pos2, this.currentBodyMessage, GuiData.smallfont, new Color?(Color.White * 0.8f), (float)dest.Width / 2f, 30f, false);
            int  height = 40;
            int  width  = 450;
            bool flag2  = !this.showLoadingSpinner;

            if (!this.isInUpload)
            {
                if (Button.doButton(371711001, (int)vector2.X, (int)vector2.Y, width, height, flag1 ? " - Item Created -" : "Create Entry in Steam Workshop", new Color?(flag1 ? Color.LightBlue : Color.Gray)) && !flag1 && flag2)
                {
                    this.CreateExtensionInSteam(info);
                }
                vector2.Y += (float)(height + 4);
                if (Button.doButton(371711003, (int)vector2.X, (int)vector2.Y, width, height, "Upload to Steam Workshop", new Color?(flag1 ? Color.LightBlue : Color.Gray)) && flag2)
                {
                    this.PerformUpdate(info);
                }
                vector2.Y += (float)(height + 4);
                if (Button.doButton(371711005, (int)vector2.X, (int)vector2.Y + 10, width, height - 10, "Back to Extension Menu", new Color?(Color.Black)) && flag2 && this.GoBack != null)
                {
                    this.GoBack();
                }
                vector2.Y += (float)(height + 4);
            }
            return(vector2);
        }
示例#54
0
        private void frmCapture_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _onClick     = false;
                _donedrawing = true;
            }
            else if (e.Button == MouseButtons.Right)
            {
                clipboardToolStripMenuItem.Enabled = (Clipboard.ContainsImage() || Common.ImageFileInClipboard || Common.ImageUrlInClipboard);
            }

            if (_donedrawing)
            {
                _otherformopen = true;
                Hide();

                bool ValidRectangle = !(pbSelection.Size.Width == 0 && pbSelection.Size.Height == 0);
                if (_mouseMoved && ValidRectangle)
                {
                    if (pbSelection.Size.Width == 0 || pbSelection.Size.Height == 0)
                    {
                        string errorcase = (MousePosition.X == pbSelection.Location.X) ? "width" : "height";
                        string msg       = string.Format("Image {0} cannot be null", errorcase);
                        MessageBox.Show(null, msg, "upScreen", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Common.KillOrWait(true);
                        return;
                    }

                    // Calculate the final selected area
                    // Location should be relative to the screen we are capturing
                    var s_FinalPoint = MousePosition.Substract(CaptureControl.CaptureScreen.Bounds.Location);

                    var s_LeftX   = s_FinalPoint.X > NativeClickPoint.X ? NativeClickPoint.X : s_FinalPoint.X;
                    var s_RightX  = s_FinalPoint.X <= NativeClickPoint.X ? NativeClickPoint.X : s_FinalPoint.X;
                    var s_TopY    = s_FinalPoint.Y > NativeClickPoint.Y ? NativeClickPoint.Y : s_FinalPoint.Y;
                    var s_BottomY = s_FinalPoint.Y <= NativeClickPoint.Y ? NativeClickPoint.Y : s_FinalPoint.Y;

                    var s_Width  = s_RightX - s_LeftX;
                    var s_Height = s_BottomY - s_TopY;

                    // Capture the selected area
                    Rectangle area = new Rectangle(s_LeftX, s_TopY, s_Width, s_Height);
                    CaptureControl.CaptureArea(area);
                }
                else
                {
                    try
                    {
                        // when single-clicking over the taskbar, capture it. Otherwise, capture the window from the cursor point
                        if (NativeClickPoint.Y > CaptureControl.CaptureScreen.WorkingArea.Height)
                        {
                            Rectangle taskbar = new Rectangle(0, CaptureControl.CaptureScreen.WorkingArea.Height, CaptureControl.CaptureScreen.Bounds.Width, CaptureControl.CaptureScreen.Bounds.Height - CaptureControl.CaptureScreen.WorkingArea.Height);
                            CaptureControl.CaptureArea(taskbar);
                        }
                        else
                        {
                            CaptureControl.CaptureWindow(Cursor.Position);
                        }
                    }
                    catch
                    {
                        Common.KillOrWait(true);
                    }
                }
            }
        }
示例#55
0
        /// <summary>
        /// Meanshift algorithm
        /// </summary>
        /// <param name="probabilityMap">Probability map [0-1].</param>
        /// <param name="roi">Initial search area</param>
        /// <param name="termCriteria">Mean shift termination criteria.</param>
        /// <returns>Object area.</returns>
        public static Rectangle Process(Image <Gray, byte> probabilityMap, Rectangle roi, TermCriteria termCriteria)
        {
            CentralMoments centralMoments;

            return(process(probabilityMap, roi, termCriteria, out centralMoments));
        }
示例#56
0
 public Drawable(Rectangle _Rect)
 {
     Rect = _Rect;
     OverRect = new Rectangle(Rect.X - 1, Rect.Y - 1, Rect.Width + 2, Rect.Height + 2);
 }
示例#57
0
 public Tile(string assetName, Rectangle srcRect)
     : this()
 {
     SourceRect  = srcRect;
     Spritesheet = assetName;
 }
示例#58
0
        /// <summary>
        /// Meanshift algorithm
        /// </summary>
        /// <param name="probabilityMap">Probability map [0-1].</param>
        /// <param name="roi">Initial search area</param>
        /// <returns>Object area.</returns>
        public static Rectangle Process(Image <Gray, byte> probabilityMap, Rectangle roi)
        {
            CentralMoments centralMoments;

            return(process(probabilityMap, roi, DEFAULT_TERM, out centralMoments));
        }
        /// <summary>
        /// Draw text without a glowing background, for use on a composition element.
        /// </summary>
        /// <param name="g">Graphics reference.</param>
        /// <param name="text">Text to be drawn.</param>
        /// <param name="font">Font to use for text.</param>
        /// <param name="bounds">Bounding area for the text.</param>
        /// <param name="state">State of the source element.</param>
        /// <param name="color"><see cref="Color"/> of the text.</param>
        /// <param name="copyBackground">Should existing background be copied into the bitmap.</param>
        /// <param name="sf">StringFormat of the memento.</param>
        public static void DrawCompositionText(Graphics g,
                                                      string text,
                                                      Font font,
                                                      Rectangle bounds,
                                                      PaletteState state,
                                                      Color color,
                                                      bool copyBackground,
                                                      StringFormat sf)
        {
            // Get the hDC for the graphics instance and create a memory DC
            IntPtr gDC = g.GetHdc();
            try
            {
                IntPtr mDC = PI.CreateCompatibleDC(gDC);

                PI.BITMAPINFO bmi = new PI.BITMAPINFO();
                bmi.biSize = Marshal.SizeOf(bmi);
                bmi.biWidth = bounds.Width;
                bmi.biHeight = -(bounds.Height);
                bmi.biCompression = 0;
                bmi.biBitCount = 32;
                bmi.biPlanes = 1;

                // Create a device independent bitmap and select into the memory DC
                IntPtr hDIB = PI.CreateDIBSection(gDC, bmi, 0, 0, IntPtr.Zero, 0);
                PI.SelectObject(mDC, hDIB);

                if (copyBackground)
                {
                    // Copy existing background into the bitmap
                    PI.BitBlt(mDC, 0, 0, bounds.Width, bounds.Height,
                              gDC, bounds.X, bounds.Y, 0x00CC0020);
                }

                // Select the font for use when drawing
                IntPtr hFont = font.ToHfont();
                PI.SelectObject(mDC, hFont);

                // Get renderer for the correct state
                VisualStyleRenderer renderer = new VisualStyleRenderer(state == PaletteState.Normal ? VisualStyleElement.Window.Caption.Active :
                                                                                                      VisualStyleElement.Window.Caption.Inactive);

                // Create structures needed for theme drawing call
                PI.RECT textBounds = new PI.RECT
                {
                    left = 0,
                    top = 0,
                    right = (bounds.Right - bounds.Left),
                    bottom = (bounds.Bottom - bounds.Top)
                };
                PI.DTTOPTS dttOpts = new PI.DTTOPTS
                {
                    dwSize = Marshal.SizeOf(typeof(PI.DTTOPTS)),
                    dwFlags = PI.DTT_COMPOSITED | PI.DTT_TEXTCOLOR,
                    crText = ColorTranslator.ToWin32(color)
                };

                // Always draw text centered
                TextFormatFlags textFormat = TextFormatFlags.SingleLine |
                                             TextFormatFlags.HorizontalCenter |
                                             TextFormatFlags.VerticalCenter;
                ////Seb   |  TextFormatFlags.EndEllipsis;


                // Perform actual drawing
                //PI.DrawThemeTextEx(renderer.Handle,
                //                   mDC, 0, 0,
                //                   text, -1, (int)StringFormatToFlags(sf),
                //                   ref textBounds, ref dttOpts);
                PI.DrawThemeTextEx(renderer.Handle,
                                  mDC, 0, 0,
                                  text, -1, (int)textFormat,
                                  ref textBounds, ref dttOpts);

                // Copy to foreground
                PI.BitBlt(gDC,
                          bounds.Left, bounds.Top,
                          bounds.Width, bounds.Height,
                          mDC, 0, 0, 0x00CC0020);

                // Dispose of allocated objects
                PI.DeleteObject(hFont);
                PI.DeleteObject(hDIB);
                PI.DeleteDC(mDC);

               
            }
            catch
            {
                // ignored
            }
            finally
            {
                // Must remember to release the hDC
                g.ReleaseHdc(gDC);
            }
        }
示例#60
0
 /// <summary>
 /// Calculates if a point is within the shape that defines the element
 /// </summary>
 /// <param name="point">A point to test in the virtual modeling plane</param>
 /// <returns></returns>
 public override bool PointInElement(Point point)
 {
     Rectangle temp = new Rectangle(point, new Size(1, 1));
     temp.Inflate(2, 2);
     return ElementInRectangle(temp);
 }