Example #1
1
 public override void Draw(Graphics gr)
 {
     if (Ready)
         {
             gr.DrawRectangle(Pens.Green, Left, Top, Right, Bottom);
         }
 }
Example #2
0
 public static void Draw(Graphics.Texture texture, float x, float y, float width, float height, Color color, float depth)
 {
     if (Settings.actualScreenWidth / Settings.actualScreenHeight < (Settings.renderWidth / (float)Settings.renderHeight))
     {
         Stator.spriteBatch.Draw(texture.texture, new Rectangle((int)(x * Settings.actualScreenWidth),
             (int)((Settings.actualScreenHeight - Settings.actualScreenWidth / (Settings.renderWidth / (float)Settings.renderHeight)) / 2 + y * Settings.actualScreenWidth),
             (int)(width * Settings.actualScreenWidth) + 1,
             (int)(height * Settings.actualScreenWidth) + 1),
             null,
             color,
             0,
             new Vector2(0, 0),
             SpriteEffects.None,
             depth);
     }
     else
     {
         Stator.spriteBatch.Draw(texture.texture, new Rectangle((int)((Settings.actualScreenWidth - Settings.actualScreenHeight * (Settings.renderWidth / (float)Settings.renderHeight)) / 2 + x * Settings.actualScreenHeight),
             (int)(y * Settings.actualScreenHeight),
             (int)(width * Settings.actualScreenHeight) + 1,
             (int)(height * Settings.actualScreenHeight) + 1),
             null,
             color,
             0,
             new Vector2(0, 0),
             SpriteEffects.None,
             depth);
     }
 }
        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);
              }
        }
		public override void WriteInstance( Serialization.MaterialSerializer ser, SubRenderState subRenderState,
		                                    Graphics.Pass srcPass, Graphics.Pass dstPass )
		{
			//TODO
			//ser.WriteAttribute(4, "lighting_stage");
			//ser.WriteValue("per_pixel");
		}
        public static void Run()
        {
            // ExStart:AddWatermarkToImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();

            // Create an instance of Image and load an existing image
            using (Image image = Image.Load(dataDir + "WaterMark.bmp"))
            {
                // Create and initialize an instance of Graphics class
                Graphics graphics = new Graphics(image);

                // Creates an instance of Font
                Font font = new Font("Times New Roman", 16, FontStyle.Bold);

                // Create an instance of SolidBrush and set its various properties
                SolidBrush brush = new SolidBrush();
                brush.Color = Color.Black;
                brush.Opacity = 100;

                // Draw a String using the SolidBrush object and Font, at specific Point and Save the image with changes.
                graphics.DrawString("Aspose.Imaging for .Net", font, brush, new PointF(image.Width / 2, image.Height / 2));
                image.Save(dataDir + "AddWatermarkToImage_out.bmp");
                // ExStart:AddWatermarkToImage

                // Display Status.
                Console.WriteLine("Watermark added successfully.");
               
            }
        }
 public override void Draw(Graphics e)
 {
     Point[] PointArray = new Point[PointList.Count];
     PointArray = PointList.ToArray();
     for (int i = 0; i < PointList.Count; i++)
         e.DrawLines(new Pen(Color.Black), PointArray);
 }
        internal void Init(Graphics.GUI.MyGuiControlTabPage infoPage, MyCubeGrid grid)
        {
            m_grid = grid;
            m_infoPage = infoPage;
            Debug.Assert(m_infoPage != null);

            RecreateControls();

            if (grid == null)
                return;
            grid.OnBlockAdded += grid_OnBlockAdded;
            grid.OnBlockRemoved += grid_OnBlockRemoved;
            grid.OnPhysicsChanged += grid_OnPhysicsChanged;
            grid.OnBlockOwnershipChanged += grid_OnBlockOwnershipChanged;

            if (MyFakes.ENABLE_TERMINAL_PROPERTIES)
            {
                var renameShipBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("RenameShipButton");
                if (renameShipBtn != null)
                    renameShipBtn.ButtonClicked += renameBtn_ButtonClicked;
            }

            var convertBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertBtn");
            if (convertBtn != null)
            {
                convertBtn.ButtonClicked += convertBtn_ButtonClicked;
            }
        }
        public static void Run()
        {
            // ExStart:DrawingBezier
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();

            // Creates an instance of FileStream
            using (FileStream stream = new FileStream(dataDir + "DrawingArc_out.bmp", FileMode.Create))
            {
                // Create an instance of BmpOptions and set its various properties
                BmpOptions saveOptions = new BmpOptions();
                saveOptions.BitsPerPixel = 32;

                // Set the Source for BmpOptions and create an instance of Image
                saveOptions.Source = new StreamSource(stream);               
                using (Image image = Image.Create(saveOptions, 100, 100))
                {
                    // Create and initialize an instance of Graphics class and clear Graphics surface
                    Graphics graphic = new Graphics(image);
                    graphic.Clear(Color.Yellow);

                    // Draw an arc shape by specifying the Pen object having red black color and coordinates, height, width, start & end angles                 
                    int width = 100;
                    int height = 200;
                    int startAngle = 45;
                    int sweepAngle = 270;

                    // Draw arc to screen and save all changes.
                    graphic.DrawArc(new Pen(Color.Black), 0, 0, width, height, startAngle, sweepAngle);
                    image.Save();
                }
                stream.Close();
            }
        }
        public override void draw(Graphics g, CoordinateFrame scale)
        {
            if (collisionManager is GridCollision)
            {
                GridCollision gc = (GridCollision)collisionManager;
                gc.draw(g, scale);
            }

            if (environment != null)
            {
                environment.draw(g, scale);
            }

            foreach (Robot robot in robots)
            {
                robot.draw(g, scale);
            }
            double[] obj = null;

            instance_pack ip = new instance_pack();

            ip.robots = robots;
            ip.env=environment;
            ip.timeSteps = this.timeSteps;
            ip.agentBrain = agentBrain;
            ip.collisionManager = collisionManager;
            ip.elapsed = this.elapsed;
            ip.ff = this.fitnessFunction;
            ip.bc = this.behaviorCharacterization;
            ip.timestep=timestep;

            g.DrawString("Fitness: " + this.fitnessFunction.calculate(this, this.environment, ip, out obj), new Font("Tahoma", 12), Brushes.Black, 10, 90);
            g.DrawString("Elapsed time: " + this.elapsed, new Font("Tahoma", 12), Brushes.Black, 10, 60);
        }
    // Use this for initialization
    void Start()
    {
        curve = new Curve();

        graphics = new Graphics();
        graphics.verticesDrawer = verticesDrawer;
    }
 public Entity_SkyBox(Graphics.Entity.Model model)
 {
     m_model = model;
     m_position = new Vector3(0.0f, 0.0f, 0.0f);
     m_scale = new Vector3(10.0f, 10.0f, 10.0f);
     m_rotation = Vector3.Zero;
 }
Example #12
0
 public override void Draw(Graphics gr)
 {
     if (Ready)
         {
             gr.DrawLine(Pens.Green, First, Second);
         }
 }
 public PrintPageEventArgs(Graphics graphics, Rectangle marginBounds, Rectangle pageBounds, PageSettings pageSettings)
 {
     Graphics = graphics;
     MarginBounds = marginBounds;
     PageBounds = pageBounds;
     PageSettings = pageSettings;
 }
Example #14
0
        void DrawStreched(Graphics g, Rectangle dest)
        {
            g.Draw(texture, new Rectangle(dest.X, dest.Y, paddingLeft, paddingTop),
                            new Rectangle(0, 0, paddingLeft, paddingTop), border);

            g.Draw(texture, new Rectangle(dest.X + paddingLeft, dest.Y, dest.Width - paddingLeft - paddingRight, paddingTop),
                            new Rectangle(paddingLeft, 0, texture.Width - paddingLeft - paddingRight, paddingTop), border);

            g.Draw(texture, new Rectangle(dest.X + dest.Width - paddingRight, dest.Y, paddingLeft, paddingTop),
                            new Rectangle(texture.Width - paddingRight, 0, paddingLeft, paddingTop), border);

            g.Draw(texture, new Rectangle(dest.X, dest.Y + paddingTop, paddingLeft, dest.Height - paddingTop - paddingBottom),
                            new Rectangle(0, paddingTop, paddingLeft, texture.Height - paddingTop - paddingBottom), border);

            g.Draw(texture, new Rectangle(dest.X + paddingLeft, dest.Y + paddingTop, dest.Width - paddingLeft - paddingRight, dest.Height - paddingTop - paddingBottom),
                            new Rectangle(paddingLeft, paddingTop, texture.Width - paddingLeft - paddingRight, texture.Height - paddingLeft - paddingRight), color);

            g.Draw(texture, new Rectangle(dest.X + dest.Width - paddingRight, dest.Y + paddingTop, paddingRight, dest.Height - paddingTop - paddingBottom),
                            new Rectangle(texture.Width - paddingRight, paddingTop, paddingRight, texture.Height - paddingTop - paddingBottom), border);

            g.Draw(texture, new Rectangle(dest.X, dest.Y + dest.Height - paddingBottom, paddingLeft, paddingBottom),
                            new Rectangle(0, texture.Height - paddingBottom, paddingLeft, paddingBottom), border);

            g.Draw(texture, new Rectangle(dest.X + paddingLeft, dest.Y + dest.Height - paddingBottom, dest.Width - paddingLeft - paddingRight, paddingBottom),
                            new Rectangle(paddingLeft, texture.Height - paddingBottom, texture.Width - paddingLeft - paddingRight, paddingBottom), border);

            g.Draw(texture, new Rectangle(dest.X + dest.Width - paddingRight, dest.Y + dest.Height - paddingBottom, paddingLeft, paddingBottom),
                            new Rectangle(texture.Width - paddingRight, texture.Height - paddingBottom, paddingLeft, paddingBottom), border);
        }
        public static void Run()
        {
            // ExStart:DrawingUsingGraphics
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleImage_out.bmp";

            // Create an instance of BmpOptions and set its various properties
            BmpOptions imageOptions = new BmpOptions();
            imageOptions.BitsPerPixel = 24;

            // Create an instance of FileCreateSource and assign it to Source property 
            imageOptions.Source = new FileCreateSource(dataDir, false);
            using (var image =  Image.Create(imageOptions, 500, 500))
            {
                var graphics = new Graphics(image);

                // Clear the image surface with white color and Create and initialize a Pen object with blue color
                graphics.Clear(Color.White);                
                var pen = new Pen(Color.Blue);

                // Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
                graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
                using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
                {
                    graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
                }
                image.Save();
            }
            // ExEnd:DrawingUsingGraphics
        }
Example #16
0
    public void Draw(Graphics graphics, Size buffersize)
    {
        //store transform, (like opengl's glPushMatrix())
        Matrix mat1 = graphics.Transform;

        //transform into position
        graphics.TranslateTransform(m_position.X, m_position.Y);
        graphics.RotateTransform(m_angle/(float)Math.PI * 180.0f);

        try
        {
            //draw body
            graphics.DrawRectangle(new Pen(m_color), rect);

            //draw line in the "forward direction"
            graphics.DrawLine(new Pen(Color.Yellow), 1, 0, 1, 5);
        }
        catch(OverflowException exc)
        {
            //physics overflow :(
        }

        //restore transform
        graphics.Transform = mat1;
    }
Example #17
0
 public Shader( IGraphicsDevice graphicsDevice, Stream stream, Graphics.ShaderType shaderType )
     : this(graphicsDevice, shaderType)
 {
     byte [] shaderCode = new byte [ stream.Length ];
     stream.Read ( shaderCode, 0, shaderCode.Length );
     SetShaderAndCompile ( Encoding.UTF8.GetString ( shaderCode ) );
 }
        void RenderModel(Graphics.Content.Model10 model, SlimDX.Matrix entityWorld, Effect effect)
        {
            throw new NotImplementedException();
            //if (model == null || !model.Visible || model.Mesh == null) return;

            Matrix world = model.World * entityWorld;
            world.M41 = (float)((int)world.M41);
            world.M42 = (float)((int)world.M42);
            world *= Matrix.Scaling(2f / (float)view.Viewport.Width, 2f / (float)view.Viewport.Height, 1) * Matrix.Translation(-1, -1, 0) * Matrix.Scaling(1, -1, 1);
            world.M43 = 0.5f;

            effect.GetVariableByName("World").AsMatrix().SetMatrix(world);
            effect.GetVariableByName("Texture").AsResource().SetResource(model.TextureShaderView);

            effect.GetTechniqueByName("Render").GetPassByIndex(0).Apply();
            if (model.Mesh != null)
            {
                model.Mesh.Setup(view.Device10, view.Content.Acquire<InputLayout>(
                    new Content.VertexStreamLayoutFromEffect
                {
                    Signature10 = effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                    Layout = model.Mesh.VertexStreamLayout
                }));

                model.Mesh.Draw(device);
            }
        }
Example #19
0
		internal void ReleasePrograms( Graphics.Pass pass, TargetRenderState renderState )
		{
			ProgramSet programSet = renderState.ProgramSet;

			pass.SetVertexProgram( string.Empty );
			pass.SetFragmentProgram( string.Empty );

			renderState.DestroyProgramSet();

			foreach ( var key in this.vertexShaderMap.Keys )
			{
				if ( true ) //TODO
				{
					DestroyGpuProgram( this.vertexShaderMap[ key ] );
					this.vertexShaderMap.Remove( key );
					break;
				}
			}

			foreach ( var key in this.fragmentShaderMap.Keys )
			{
				if ( true )
				{
					DestroyGpuProgram( this.fragmentShaderMap[ key ] );
					this.fragmentShaderMap.Remove( key );
					break;
				}
			}
		}
Example #20
0
        public void Draw(Graphics.Renderer renderer)
        {
            /*
            if (texture == null)
                texture = ResourceManager.Load<Texture2D>("GUI/BackgroundBlack");

            Main.renderer.Draw(Graphics.GraphicsEngine.pixel,
                new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y),
                new Rectangle(0, 0, (int)size.X, (int)size.Y),
                Color.Black * 0.5f);
            Main.renderer.Draw(texture,
                new Rectangle((int)position.X, (int)position.Y, (int)4, (int)4),
                new Rectangle(0, 0, (int)4, (int)4),
                Color.White);
            Main.renderer.Draw(texture,
                new Rectangle((int)(position.X + size.X - 4), (int)position.Y, (int)4, (int)4),
                new Rectangle(252, 0, (int)4, (int)4),
                Color.White);
            Main.renderer.Draw(texture,
                new Rectangle((int)position.X, (int)(position.Y + size.Y - 4), (int)4, (int)4),
                new Rectangle(0, 252, (int)4, (int)4),
                Color.White);
            Main.renderer.Draw(texture,
                new Rectangle((int)(position.X + size.X - 4), (int)(position.Y + size.Y - 4), 4, 4),
                new Rectangle(252, 252, 4, 4),
                Color.White);//*/
            view.Draw(renderer);
        }
Example #21
0
	public static bool Run(Graphics graphPort, Bitmap dstBitmap, Bitmap srcBitmap, Rectangle frame, int iterations)
	{
		IntPtr realDC = graphPort.GetHdc();
		//IntPtr hDCDst = Graphics.FromImage(dstBitmap).GetHdc(true);
		IntPtr hDCDst = Graphics.FromImage(dstBitmap).GetHdc();
		int XDst = 0;
		int YDst = 0;
		int nDstW = dstBitmap.Width;
		int nDstH = dstBitmap.Height;
		//IntPtr hDCSrc = Graphics.FromImage(srcBitmap).GetHdc(true);
		IntPtr hDCSrc = Graphics.FromImage(srcBitmap).GetHdc();
		int XSrc = 0;
		int YSrc = 0;
		int nSrcW = srcBitmap.Width;
		int nSrcH = srcBitmap.Height;

		//bool success = StretchBlt(realDC, frame.Left, frame.Top, frame.Width, frame.Height, hDCSrc, 0, 0, nDstW, nDstH, SRCCOPY);

		
		for (int i = iterations; i >= 1; i--)
		{
			BLENDFUNCTION blender = new BLENDFUNCTION(AC_SRC_OVER, 0, (byte)(255 / i), 0);
			if (!AlphaBlend(hDCDst, XDst, YDst, nDstW, nDstH,
				hDCSrc, XSrc, YSrc, nSrcW, nSrcH, blender))
				return false;

			bool success = StretchBlt(realDC, frame.Left, frame.Top, frame.Width, frame.Height, hDCDst, 0, 0, nDstW, nDstH, SRCCOPY);
		}
		
		return true;
	}
Example #22
0
 public override void Draw(Graphics g, Rectangle dest)
 {
     foreach (Box b in boxes)
     {
         b.Draw(g, dest);
     }
 }
	// Constructor, which saves away all of the important information.
	// We assume that the lock on the "graphics" object is held by the caller.
	internal GraphicsContainer(Graphics graphics)
			{
				// Push this container onto the stack.
				this.graphics = graphics;
				next = graphics.stackTop;
				graphics.stackTop = this;

				// Save the graphics state information.
				clip = graphics.Clip;
				if(clip != null)
				{
					clip = clip.Clone();
				}
				compositingMode = graphics.CompositingMode;
				compositingQuality = graphics.CompositingQuality;
				interpolationMode = graphics.InterpolationMode;
				pageScale = graphics.PageScale;
				pageUnit = graphics.PageUnit;
				pixelOffsetMode = graphics.PixelOffsetMode;
				renderingOrigin = graphics.RenderingOrigin;
				smoothingMode = graphics.SmoothingMode;
				textContrast = graphics.TextContrast;
				textRenderingHint = graphics.TextRenderingHint;
				if (graphics.transform == null)
				{
					transform = null;
				}
				else
				{
					transform = Matrix.Clone(graphics.transform);
				}
			}
    protected override void ApplyTextWatermark(ImageProcessingActionExecuteArgs args, Graphics g)
    {
        // Draw a filled rectangle
        int rectangleWidth = 14;
        using (Brush brush = new SolidBrush(Color.FromArgb(220, Color.Red)))
        {
            g.FillRectangle(brush, new Rectangle(args.Image.Size.Width - rectangleWidth, 0, rectangleWidth, args.Image.Size.Height));
        }

        using (System.Drawing.Drawing2D.Matrix transform = g.Transform)
        {
            using (StringFormat stringFormat = new StringFormat())
            {
                // Vertical text (bottom -> top)
                stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
                transform.RotateAt(180F, new PointF(args.Image.Size.Width / 2, args.Image.Size.Height / 2));
                g.Transform = transform;

                // Align: top left, +2px displacement 
                // (because of the matrix transformation we have to use inverted values)
                base.ContentAlignment = ContentAlignment.MiddleLeft;
                base.ContentDisplacement = new Point(-2, -2);

                base.ForeColor = Color.White;
                base.Font.Size = 10;

                // Draw the string by invoking the base Apply method
                base.StringFormat = stringFormat;
                base.ApplyTextWatermark(args, g);
                base.StringFormat = null;
            }
        }
    }
Example #25
0
 /// <summary>
 /// Gets the baseline Height of the rectangle
 /// </summary>
 /// <param name="g"></param>
 /// <returns></returns>
 public float GetBaseLineHeight(CssBox b, Graphics g)
 {
     Font f = b.ActualFont;
     FontFamily ff = f.FontFamily;
     FontStyle s = f.Style;
     return f.GetHeight(g) * ff.GetCellAscent(s) / ff.GetLineSpacing(s);
 }
Example #26
0
 public virtual void Render(Graphics g)
 {
     for (int i = 0; i < _Particles.Count; i++)
     {
         _Particles[i].Render(g);
     }
 }
Example #27
0
		public void Draw(Graphics g, int x, int y, int frame)
		{
			north[frame].Draw(g,x,y-(int)((PckImage.Width*PckImage.Scale)/2));
			south[frame].Draw(g,x,y);
			east[frame].Draw(g,x+(int)((PckImage.Width*PckImage.Scale)/2),y-(int)((PckImage.Width*PckImage.Scale)/4));
			west[frame].Draw(g,x-(int)((PckImage.Width*PckImage.Scale)/2),y-(int)((PckImage.Width*PckImage.Scale)/4));	
		}
        public static void Run()
        {
            // ExStart:DrawingRectangle
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages() + "SampleRectangle_out.bmp";

            // Creates an instance of FileStream
            using (FileStream stream = new FileStream(dataDir, FileMode.Create))
            {
                // Create an instance of BmpOptions and set its various properties
                BmpOptions saveOptions = new BmpOptions();
                saveOptions.BitsPerPixel = 32;

                // Set the Source for BmpOptions and Create an instance of Image
                saveOptions.Source = new StreamSource(stream);
                using (Image image = Image.Create(saveOptions, 100, 100))
                {
                    // Create and initialize an instance of Graphics class,  Clear Graphics surface, Draw a rectangle shapes and  save all changes.
                    Graphics graphic = new Graphics(image);
                    graphic.Clear(Color.Yellow);
                    graphic.DrawRectangle(new Pen(Color.Red), new Rectangle(30, 10, 40, 80));
                    graphic.DrawRectangle(new Pen(new SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
                    image.Save();
                }
            }
            // ExEnd:DrawingRectangle
        }
	// Restore a graphics object back to the state of this container.
	// We assume that the lock on the "graphics" object is held by the caller.
	internal void Restore(Graphics graphics)
			{
				// Bail out if the container applies to something else.
				if(graphics != this.graphics)
				{
					return;
				}

				// Make sure that we are on the stack, and pop it and all
				// of the items above it.  Bail out if not on the stack.
				GraphicsContainer container = graphics.stackTop;
				while(container != null && container != this)
				{
					container = container.next;
				}
				if(container == null)
				{
					return;
				}
				graphics.stackTop = next;

				// Restore the "graphics" object to its previous state.
				graphics.Clip = clip;
				graphics.CompositingMode = compositingMode;
				graphics.CompositingQuality = compositingQuality;
				graphics.InterpolationMode = interpolationMode;
				graphics.PageScale = pageScale;
				graphics.PageUnit = pageUnit;
				graphics.PixelOffsetMode = pixelOffsetMode;
				graphics.RenderingOrigin = renderingOrigin;
				graphics.SmoothingMode = smoothingMode;
				graphics.TextContrast = textContrast;
				graphics.TextRenderingHint = textRenderingHint;
				graphics.Transform = transform;
			}
Example #30
0
        public CylinderPrimitive(Graphics graphicsDevice)
        {
            Debug.Assert (_tessellation >= 3);

            // Create a ring of triangles around the outside of the cylinder.
            for (int i = 0; i <= _tessellation; i++) {
                Vector3 normal = GetCircleVector (i, _tessellation);

                Vector3 topPos = normal * _radius + Vector3.Up * _height;
                Vector3 botPos = normal * _radius + Vector3.Down * _height;

                AddVertex (topPos, normal);
                AddVertex (botPos, normal);
            }

            for (int i = 0; i < _tessellation; i++) {
                AddIndex (i * 2);
                AddIndex (i * 2 + 1);
                AddIndex ((i * 2 + 2));

                AddIndex (i * 2 + 1);
                AddIndex (i * 2 + 3);
                AddIndex (i * 2 + 2);
            }

            // Create flat triangle fan caps to seal the top and bottom.
            CreateCap (_tessellation, _height, _radius, Vector3.Up);
            CreateCap (_tessellation, _height, _radius, Vector3.Down);

            InitializePrimitive (graphicsDevice);
        }
Example #31
0
        /*public byte Opacity
         * {
         *      get
         *      {
         *              return m_parentProjectedLayer.Opacity;
         *      }
         *      set
         *      {
         *              if(m_NwImageLayer != null)
         *              {
         *                      m_NwImageLayer.Opacity = value;
         *              }
         *              if(m_NeImageLayer != null)
         *              {
         *                      m_NeImageLayer.Opacity = value;
         *              }
         *              if(m_SwImageLayer != null)
         *              {
         *                      m_SwImageLayer.Opacity = value;
         *              }
         *              if(m_SeImageLayer != null)
         *              {
         *                      m_SeImageLayer.Opacity = value;
         *              }
         *
         *              if(m_NorthWestChild != null)
         *              {
         *                      m_NorthWestChild.Opacity = value;
         *              }
         *              if(m_NorthEastChild != null)
         *              {
         *                      m_NorthEastChild.Opacity = value;
         *              }
         *              if(m_SouthWestChild != null)
         *              {
         *                      m_SouthWestChild.Opacity = value;
         *              }
         *              if(m_SouthEastChild != null)
         *              {
         *                      m_SouthEastChild.Opacity = value;
         *              }
         *      }
         * }*/

        private Renderable.ImageLayer CreateImageLayer(double north, double south, double west, double east, DrawArgs drawArgs, string imagePath)
        {
            Bitmap   b = null;
            Graphics g = null;

            Renderable.ImageLayer imageLayer = null;
            GeographicBoundingBox geoBB      = new GeographicBoundingBox(north, south, west, east);
            int numberPolygonsInTile         = 0;

            FileInfo imageFile = new FileInfo(imagePath);

            if (!m_parentProjectedLayer.EnableCaching ||
                !imageFile.Exists
                )
            {
                if (m_parentProjectedLayer.LineStrings != null)
                {
                    for (int i = 0; i < m_parentProjectedLayer.LineStrings.Length; i++)
                    {
                        if (!m_parentProjectedLayer.LineStrings[i].Visible)
                        {
                            continue;
                        }

                        GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.LineStrings[i].GetGeographicBoundingBox();

                        if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB))
                        {
                            continue;
                        }
                        else
                        {
                            if (b == null)
                            {
                                b = new Bitmap(
                                    m_parentProjectedLayer.TileSize.Width,
                                    m_parentProjectedLayer.TileSize.Height,
                                    System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            }

                            if (g == null)
                            {
                                g = Graphics.FromImage(b);
                            }

                            drawLineString(
                                m_parentProjectedLayer.LineStrings[i],
                                g,
                                geoBB,
                                b.Size
                                );

                            numberPolygonsInTile++;
                        }
                    }
                }

                if (m_parentProjectedLayer.Polygons != null)
                {
                    for (int i = 0; i < m_parentProjectedLayer.Polygons.Length; i++)
                    {
                        if (!m_parentProjectedLayer.Polygons[i].Visible)
                        {
                            continue;
                        }

                        GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.Polygons[i].GetGeographicBoundingBox();

                        if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB))
                        {
                            continue;
                        }
                        else
                        {
                            if (b == null)
                            {
                                b = new Bitmap(
                                    m_parentProjectedLayer.TileSize.Width,
                                    m_parentProjectedLayer.TileSize.Height,
                                    System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            }

                            if (g == null)
                            {
                                g = Graphics.FromImage(b);
                            }
                            drawPolygon(
                                m_parentProjectedLayer.Polygons[i],
                                g,
                                geoBB,
                                b.Size);

                            numberPolygonsInTile++;
                        }
                    }
                }
            }

            if (b != null)
            {
                System.Drawing.Imaging.BitmapData srcInfo = b.LockBits(new Rectangle(0, 0,
                                                                                     b.Width, b.Height),
                                                                       System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                                                       System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                bool isBlank = true;
                unsafe
                {
                    int *srcPointer = (int *)srcInfo.Scan0;
                    for (int i = 0; i < b.Height; i++)
                    {
                        for (int j = 0; j < b.Width; j++)
                        {
                            int color = *srcPointer++;

                            if (((color >> 24) & 0xff) > 0)
                            {
                                isBlank = false;
                                break;
                            }
                        }

                        srcPointer += (srcInfo.Stride >> 2) - b.Width;
                    }
                }

                b.UnlockBits(srcInfo);
                if (isBlank)
                {
                    numberPolygonsInTile = 0;
                }
            }

            //	if(!m_parentProjectedLayer.EnableCaching)
            //	{
            string id = System.DateTime.Now.Ticks.ToString();

            if (b != null && numberPolygonsInTile > 0)
            {
                MemoryStream ms = new MemoryStream();
                b.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                //must copy original stream into new stream, if not, error occurs, not sure why
                m_ImageStream = new MemoryStream(ms.GetBuffer());

                imageLayer = new WorldWind.Renderable.ImageLayer(
                    id,
                    m_parentProjectedLayer.World,
                    0,
                    m_ImageStream,
                    System.Drawing.Color.Black.ToArgb(),
                    (float)south,
                    (float)north,
                    (float)west,
                    (float)east,
                    1.0f                            //(float)m_parentProjectedLayer.Opacity / 255.0f
                    ,
                    m_parentProjectedLayer.World.TerrainAccessor);

                ms.Close();
            }

            /*	}
             *      else if(imageFile.Exists || numberPolygonsInTile > 0)
             *      {
             *              string id = System.DateTime.Now.Ticks.ToString();
             *
             *              if(b != null)
             *              {
             *                      MemoryStream ms = new MemoryStream();
             *                      b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
             *                      if(!imageFile.Directory.Exists)
             *                              imageFile.Directory.Create();
             *
             *                      //must copy original stream into new stream, if not, error occurs, not sure why
             *                      m_ImageStream = new MemoryStream(ms.GetBuffer());
             *                      ImageHelper.ConvertToDxt3(m_ImageStream, imageFile.FullName);
             *
             *                      ms.Close();
             *              }
             *
             *              imageLayer = new WorldWind.Renderable.ImageLayer(
             *                      id,
             *                      m_parentProjectedLayer.World,
             *                      0,
             *                      imageFile.FullName,
             *                      //System.Drawing.Color.Black.ToArgb(),
             *                      (float)south,
             *                      (float)north,
             *                      (float)west,
             *                      (float)east,
             *                      1.0f,//(float)m_parentProjectedLayer.Opacity / 255.0f,
             *                      m_parentProjectedLayer.World.TerrainAccessor);
             *
             *              imageLayer.TransparentColor = System.Drawing.Color.Black.ToArgb();
             *      }
             */
            if (b != null)
            {
                b.Dispose();
            }
            if (g != null)
            {
                g.Dispose();
            }

            b = null;
            g = null;

            //might not be necessary
            //GC.Collect();

            return(imageLayer);
        }
Example #32
0
 /// <summary>
 /// <para>Method that is raised when the widget needs to be
 /// painted in reponse to an <c>Expose</c> event.</para>
 /// </summary>
 ///
 /// <param name="graphics">
 /// <para>The graphics object to use to repaint the widget.  This
 /// graphics object will have been initialised with the widgets foreground
 /// and background colors, and with the clipping region set to the area
 /// that needs to be repainted.</para>
 /// </param>
 protected virtual void OnPaint(Graphics graphics)
 {
     // Nothing to do in this class.
 }
Example #33
0
 public static RectangleF[] MeasureString(this Graphics graphics, string s, Font font, Brush brush, TextPathAlign textPathAlign, TextPathPosition textPathPosition, GraphicsPath graphicsPath)
 {
     return MeasureString(graphics, s, font, brush, textPathAlign, textPathPosition, 100, graphicsPath);
 }
Example #34
0
        private void DrawText(PointF[] points, int maxPoints)
        {

            GraphicsPath gp = new GraphicsPath(_pathdata.Points, _pathdata.Types) { FillMode = FillMode.Winding };
            gp.Flatten();
            gp.Dispose();
            Graphics g = _graphics;
            GraphicsContainer graphicsContainer = g.BeginContainer();
            //g.TranslateTransform(_graphicsPath.GetBounds().X, _graphicsPath.GetBounds().Y);
            int count = 0;
            PointF point1 = default(PointF);
            int charStep = 0;
            double maxWidthText = default(double);
            int i;

            for (i = 0; i <= _text.Length - 1; i++)
            {
                maxWidthText += StringRegion(g, i);
            }

            switch (_pathalign)
            {
                case TextPathAlign.Left:
                    point1 = points[0];
                    count = 0;
                    break;
                case TextPathAlign.Center:
                    count = (int)((maxPoints - maxWidthText) / 2);
                    if (count > 0)
                    {
                        point1 = points[count];
                    }
                    else
                    {
                        point1 = points[0];
                    }

                    break;
                case TextPathAlign.Right:
                    count = (int)(maxPoints - maxWidthText - (double)StringRegion(g, _text.Length - 1) * LetterSpacePercentage / 100);
                    if (count > 0)
                    {
                        point1 = points[count];
                    }
                    else
                    {
                        point1 = points[0];
                    }

                    break;
            }

            while (!(charStep > _text.Length - 1))
            {
                int lStrWidth = (int)(StringRegion(g, charStep) * LetterSpacePercentage / 100);
                if ((count + lStrWidth / 2) >= 0 & (count + lStrWidth) < maxPoints)
                {
                    count += lStrWidth;
                    PointF point2 = points[count];
                    PointF point = points[count - lStrWidth / 2];
                    double angle = GetAngle(point1, point2);
                    DrawRotatedText(g, _text[charStep].ToString(), (float)angle, point);
                    point1 = points[count];
                }
                else
                {
                    count += lStrWidth;
                }
                charStep += 1;
            }
            g.EndContainer(graphicsContainer);
        }
Example #35
0
 /// <summary>
 /// Draw this overlay
 /// </summary>
 /// <param name="olv">The ObjectListView that is being overlaid</param>
 /// <param name="g">The Graphics onto the given OLV</param>
 /// <param name="r">The content area of the OLV</param>
 public virtual void Draw(ObjectListView olv, Graphics g, Rectangle r)
 {
 }
Example #36
0
    void EllipseDraw(bool isBtnDown = true)
    {
        if (isBtnDown && firstPoint == new Vector2(-1, -1))
        {
            var        Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(Ray, out hit))
            {
                if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
                {
                    return;
                }
                Vector2 pixelUV = hit.textureCoord;
                pixelUV.x *= fieldTexture.width;
                pixelUV.y *= fieldTexture.height;
                firstPoint = pixelUV;
            }
            return;
        }
        else if (firstPoint != new Vector2(-1, -1))
        {
            Graphics.CopyTexture(fieldTexture, savedTex);
            var        Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(Ray, out hit))
            {
                if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
                {
                    return;
                }
                Vector2 pixelUV = hit.textureCoord;
                pixelUV.x  *= fieldTexture.width;
                pixelUV.y  *= fieldTexture.height;
                secondPoint = pixelUV;

                int brushScaleX = (int)(brushSize * Field.transform.localScale.z / Field.transform.localScale.x);
                int brushScaleY = (int)(brushSize * Field.transform.localScale.x / Field.transform.localScale.z);

                float deltaX = secondPoint.x - firstPoint.x;
                float deltaY = secondPoint.y - firstPoint.y;

                Color[] colors = new Color[brushScaleX * brushScaleY];
                for (int i = 0; i < brushScaleX * brushScaleY; i++)
                {
                    colors[i] = currColor;
                }

                float xRadius  = System.Math.Abs(deltaX / 2);
                float yRadius  = System.Math.Abs(deltaY / 2);
                float angle    = 20f;
                int   segments = 1000;

                for (int i = 0; i < (segments + 1); i++)
                {
                    float x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
                    float y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;
                    savedTex.SetPixels((int)(x + firstPoint.x + deltaX / 2), (int)(y + firstPoint.y + deltaY / 2), brushScaleX, brushScaleY, colors);
                    angle += (360f / segments);
                }

                savedTex.Apply();
                fieldMaterial.mainTexture = savedTex;
            }
        }

        if (!isBtnDown)
        {
            firstPoint  = new Vector2(-1, -1);
            secondPoint = new Vector2(-1, -1);
            Graphics.CopyTexture(savedTex, fieldTexture);
            fieldMaterial.mainTexture = fieldTexture;
        }
    }
Example #37
0
    void RectDraw(bool isBtnDown = true)
    {
        if (isBtnDown && firstPoint == new Vector2(-1, -1))
        {
            var        Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(Ray, out hit))
            {
                if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
                {
                    return;
                }
                Vector2 pixelUV = hit.textureCoord;
                pixelUV.x *= fieldTexture.width;
                pixelUV.y *= fieldTexture.height;
                firstPoint = pixelUV;
            }
            return;
        }
        else if (firstPoint != new Vector2(-1, -1))
        {
            Graphics.CopyTexture(fieldTexture, savedTex);
            var        Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(Ray, out hit))
            {
                if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
                {
                    return;
                }
                Vector2 pixelUV = hit.textureCoord;
                pixelUV.x  *= fieldTexture.width;
                pixelUV.y  *= fieldTexture.height;
                secondPoint = pixelUV;

                int brushScaleX = (int)(brushSize * Field.transform.localScale.z / Field.transform.localScale.x);
                int brushScaleY = (int)(brushSize * Field.transform.localScale.x / Field.transform.localScale.z);

                float deltaX = secondPoint.x - firstPoint.x;
                float deltaY = secondPoint.y - firstPoint.y;

                Color[] colors = new Color[brushScaleX * brushScaleY];
                for (int i = 0; i < brushScaleX * brushScaleY; i++)
                {
                    colors[i] = currColor;
                }

                for (int i = 0; i <= System.Math.Abs((int)(deltaX / brushScaleX)); i++)
                {
                    int d = deltaX <= 0 ? -i : i;
                    savedTex.SetPixels((int)(firstPoint.x + d * brushScaleX), (int)firstPoint.y, brushScaleX, brushScaleY, colors);
                    savedTex.SetPixels((int)(secondPoint.x - d * brushScaleX), (int)secondPoint.y, brushScaleX, brushScaleY, colors);
                }

                for (int i = 0; i <= System.Math.Abs((int)(deltaY / brushScaleY)); i++)
                {
                    int d = deltaY <= 0 ? -i : i;
                    savedTex.SetPixels((int)firstPoint.x, (int)(firstPoint.y + d * brushScaleY), brushScaleX, brushScaleY, colors);
                    savedTex.SetPixels((int)secondPoint.x, (int)(secondPoint.y - d * brushScaleY), brushScaleX, brushScaleY, colors);
                }

                savedTex.SetPixels((int)firstPoint.x, (int)firstPoint.y, brushScaleX, brushScaleY, colors);
                savedTex.SetPixels((int)secondPoint.x, (int)secondPoint.y, brushScaleX, brushScaleY, colors);
                savedTex.SetPixels((int)(firstPoint.x + deltaX), (int)firstPoint.y, brushScaleX, brushScaleY, colors);
                savedTex.SetPixels((int)firstPoint.x, (int)(firstPoint.y + deltaY), brushScaleX, brushScaleY, colors);

                savedTex.Apply();
                fieldMaterial.mainTexture = savedTex;
            }
        }

        if (!isBtnDown)
        {
            firstPoint  = new Vector2(-1, -1);
            secondPoint = new Vector2(-1, -1);
            Graphics.CopyTexture(savedTex, fieldTexture);
            fieldMaterial.mainTexture = fieldTexture;
        }
    }
        //Copied from FormRpOutstandingIns.cs
        private void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            Rectangle bounds = e.MarginBounds;
            Graphics  g      = e.Graphics;
            string    text;
            Font      headingFont    = new Font("Arial", 13, FontStyle.Bold);
            Font      subHeadingFont = new Font("Arial", 10, FontStyle.Bold);
            int       yPos           = bounds.Top;
            int       center         = bounds.X + bounds.Width / 2;

            #region printHeading
            if (!_headingPrinted)
            {
                text = Lan.g(this, "Unfinalized Insurance Payment Report");
                g.DrawString(text, headingFont, Brushes.Black, center - g.MeasureString(text, headingFont).Width / 2, yPos);
                yPos += (int)g.MeasureString(text, headingFont).Height;
                if (comboBoxMultiType.SelectedIndices[0].ToString() == "0")
                {
                    text = "For All Types";
                }
                else
                {
                    text = "For Types: ";
                    for (int i = 0; i < comboBoxMultiType.SelectedIndices.Count; i++)
                    {
                        if (i != 0)
                        {
                            text += ", ";
                        }
                        text += _listTypes[(int)comboBoxMultiType.SelectedIndices[i]].ToString();
                    }
                }
                g.DrawString(text, subHeadingFont, Brushes.Black, center - g.MeasureString(text, subHeadingFont).Width / 2, yPos);
                yPos += (int)g.MeasureString(text, headingFont).Height;
                if (comboBoxMultiClinics.SelectedIndices[0].ToString() == "0")
                {
                    text = "For All Clinics";
                }
                else
                {
                    text = "For Clinics: ";
                    for (int i = 0; i < comboBoxMultiClinics.SelectedIndices.Count; i++)
                    {
                        if (i != 0)
                        {
                            text += ", ";
                        }
                        if (comboBoxMultiClinics.SelectedIndices[i].ToString() == "1")
                        {
                            text += "Unassigned";
                        }
                        else
                        {
                            text += _listClinics[(int)comboBoxMultiClinics.SelectedIndices[i] - 2].Abbr;
                        }
                    }
                }
                g.DrawString(text, subHeadingFont, Brushes.Black, center - g.MeasureString(text, subHeadingFont).Width / 2, yPos);
                yPos           += 20;
                _headingPrinted = true;
                _headingPrintH  = yPos;
            }
            #endregion
            yPos = gridMain.PrintPage(g, _pagesPrinted, bounds, _headingPrintH);
            _pagesPrinted++;
            if (yPos == -1)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }
            g.Dispose();
        }
Example #39
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(WebHelper.GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(WebHelper.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = WebHelper.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = WebHelper.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Example #40
0
        private void Btn_Pack_Click(object sender, RibbonControlEventArgs e)
        {
            //Connect to excel
            xlApp       = Globals.ThisAddIn.Application;
            xlWorkbook  = xlApp.ActiveWorkbook;
            xlWorksheet = xlWorkbook.ActiveSheet;

            /* 0. check if excel sheet is correct one */
            if (xlWorkbook.Name != "Sheetstock Excel.xlsx" || xlWorksheet.Name != "Calculator")
            {
                DialogResult yesNo = MessageBox.Show("The active Excel sheet does not appear to be the official Sheetstock Calculator Excel sheet. This program may not work as intended. \n\nProceed Anyway?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (yesNo == DialogResult.No)
                {
                    return;
                }
            }
            Debug.Print("Workbook: {0} -- Worksheet: {1}", xlWorkbook.Name, xlWorksheet.Name);

            Rect bounds       = new Rect();
            Rect topLeftCoord = new Rect {
                x = 0, y = 0
            };
            List <Rect> rectList = new List <Rect>();
            double      tempx, tempy;
            int         tempq, row = 2;
            Color       tempc;
            bool        b        = true;
            string      savePath = xlWorkbook.Path + "\\Sheets\\";

            /* 1. load in all data */
            #region Loading in data for sorting and packing
            //save bounds size
            tempx = xlWorksheet.Cells[3, 9].Value;
            tempy = xlWorksheet.Cells[4, 9].Value;
            if (tempx > tempy)
            {
                bounds = new Rect {
                    x = tempx, y = tempy
                }
            }
            ;
            else
            {
                bounds = new Rect {
                    x = tempy, y = tempx
                }
            };
            Debug.Print("Bounds: {0}, {1}", bounds.x, bounds.y);

            //check if first row is filled
            if (xlWorksheet.Cells[row, 1].Value == null && xlWorksheet.Cells[row, 2].Value == null && xlWorksheet.Cells[row, 3].Value == null)
            {
                MessageBox.Show("First row is not filled, or there is no input. Please make sure all data is filled properly.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //fill rectList
            while (b)
            {
                if (xlWorksheet.Cells[row, 1].Value != null && xlWorksheet.Cells[row, 2].Value != null && xlWorksheet.Cells[row, 3].Value != null && xlWorksheet.Cells[row, 4].Value != null)
                {
                    tempx = xlWorksheet.Cells[row, 1].Value;
                    tempy = xlWorksheet.Cells[row, 2].Value;
                    tempq = (int)xlWorksheet.Cells[row, 3].Value;
                    tempc = Color.FromName(xlWorksheet.Cells[row, 4].Value.ToString());
                    Debug.Print("Saving to list: x: {0}, y: {1}, quantity: {2}, color: {3}", tempx, tempy, tempq, tempc.ToKnownColor());
                    rectList.Add(new Rect {
                        x = tempx, y = tempy, quant = tempq, penColor = tempc
                    });
                    row++;
                }
                else if (xlWorksheet.Cells[row, 1].Value == null && xlWorksheet.Cells[row, 2].Value == null && xlWorksheet.Cells[row, 3].Value == null)
                {
                    b = false;
                }
                else
                {
                    MessageBox.Show("There is an incomplete row of data. Please fix.");
                    return;
                }
            }

            #endregion

            MessageBox.Show("Data imported. \n\nOutput will be printed to: " + savePath + "\n\nPlease note that any existing output files in this directory will be overwritten.",
                            "Import Complete", MessageBoxButtons.OK);
            Debug.Print("Number of objects: {0}", rectList.Count);

            //convert rectlist to rect array
            Rect[] rect = new Rect[rectList.Count];
            rect = rectList.ToArray();

            //create graphic
            Bitmap   bmp = new Bitmap(Convert.ToInt32(bounds.x * 10), Convert.ToInt32(bounds.y * 10));
            Graphics g   = Graphics.FromImage(bmp);
            g.FillRectangle(Brushes.White, new Rectangle(0, 0, Convert.ToInt32(bounds.x * 10), Convert.ToInt32(bounds.y * 10)));

            //check if output file path exists
            try
            {
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot create output directory", "Folder Creation Error", MessageBoxButtons.OK);
                return;
            }

            /* 2. sort data */
            #region sort from largest to smallest
            b = true;
            double tempD;
            Rect   tempR  = new Rect();
            Rect   absMin = new Rect {
                x = bounds.x, y = bounds.y
            };
            Rect absMax = new Rect {
                x = 0, y = 0
            };

            // sort by longest edge (x)
            for (int i = 0; i < rect.Length; i++)
            {
                // align so longest edge along x axis
                if (rect[i].x <= rect[i].y)
                {
                    tempD     = rect[i].x;
                    rect[i].x = rect[i].y;
                    rect[i].y = tempD;
                }
                if (rect[i].x < absMin.x)
                {
                    absMin = rect[i];
                }
                if (rect[i].x >= absMax.x)
                {
                    absMax = rect[i];
                }
            }
            while (b)
            {
                for (int i = 0; i < rect.Length - 1; i++)
                {
                    if (rect[i].x <= rect[i + 1].x)
                    {
                        tempR       = rect[i];
                        rect[i]     = rect[i + 1];
                        rect[i + 1] = tempR;
                    }
                }
                if (rect[0] == absMax && rect[rect.Length - 1] == absMin)
                {
                    b = false;
                }
            }
            #endregion

            /* 3. packing algorithm */
            #region piece by piece packing method
            //find total number of objects
            int quantAll = 0;
            for (int i = 0; i < rect.Length; i++)
            {
                quantAll += rect[i].quant;
            }
            Debug.Print("total # of elements: {0} \n", quantAll);

            //place 1 by 1
            Rect remainingRowArea = new Rect {
                x = bounds.x, y = bounds.y
            };
            Rect   smallestRemainingRect = new Rect();
            double nextRowx = 0;
            int    sheetNum = 1;
            int[]  counter  = new int[rect.Length];
            foreach (int i in counter)
            {
                counter[i] = 0;
            }
            bool endofSheet = false;

            for (int i = 0; i < quantAll; i++)
            {
                //If no more rectangles can be drawn
                if (i < quantAll - 1 && endofSheet)
                {
                    string message = "No more rectangles can be fitted onto this sheet, please move to next sheet. \n\n";
                    for (int j = 0; j < rect.Length; j++)
                    {
                        message += "Remaining # of " + rect[j].penColor.ToKnownColor() + " rectangles: " + (rect[j].quant - counter[j]) + "\n";
                    }
                    Debug.Print(message);
                    // save bmp, reset and start again
                    bmp.Save(savePath + "Sheet-" + sheetNum + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    g.FillRectangle(Brushes.White, new Rectangle(0, 0, Convert.ToInt32(bounds.x * 10), Convert.ToInt32(bounds.y * 10)));
                    endofSheet = false;
                    sheetNum++;
                    i--;
                    topLeftCoord.x     = 0;
                    topLeftCoord.y     = 0;
                    remainingRowArea.x = bounds.x;
                    remainingRowArea.y = bounds.y;
                }
                //find smallest remaining piece
                for (int j = rect.Length - 1; j > 0; j--)
                {
                    if (counter[j] < rect[j].quant)
                    {
                        smallestRemainingRect = rect[j];
                        break;
                    }
                }
                //if remaining area is smaller than smallest remaining piece
                if (remainingRowArea.y < smallestRemainingRect.x && remainingRowArea.y < smallestRemainingRect.y)
                {
                    // goto next row
                    topLeftCoord.y      = 0;
                    topLeftCoord.x     += nextRowx;
                    remainingRowArea.y  = bounds.y;
                    remainingRowArea.x -= nextRowx;
                    nextRowx            = 0;
                    Debug.Print("Going to next row - remaining area: {0} {1}", remainingRowArea.x, remainingRowArea.y);
                }
                //go through pre sorted rectangles (longest x to shortest)
                for (int j = 0; j < rect.Length; j++)
                {
                    //if there is enough space to fit 2 of this rectangle in current row, draw until no more fits
                    if (counter[j] < rect[j].quant && rect[j].y <= remainingRowArea.y && rect[j].x * 2 <= nextRowx)
                    {
                        Debug.Print("Instance {0} - At least 2 " + rect[j].penColor.ToKnownColor() + " Rectangles can fit here", i);
                        double originalx     = topLeftCoord.x;
                        double remainingRowx = nextRowx;
                        i--;
                        while (counter[j] < rect[j].quant && rect[j].y <= remainingRowArea.y && rect[j].x <= remainingRowx)
                        {
                            g.DrawRectangle(rect[j].pen, Convert.ToInt32(topLeftCoord.x * 10), Convert.ToInt32(topLeftCoord.y * 10), Convert.ToInt32(rect[j].x * 10), Convert.ToInt32(rect[j].y * 10));
                            topLeftCoord.x += rect[j].x;
                            remainingRowx  -= rect[j].x;
                            counter[j]++;
                            i++;
                            Debug.Print("Instance {0} - Another " + rect[j].penColor.ToKnownColor() + " Rectangle was drawn in parallel, #{1} \n", i, counter[j]);
                        }
                        topLeftCoord.x      = originalx;
                        topLeftCoord.y     += rect[j].y;
                        remainingRowArea.y -= rect[j].y;
                        break;
                    }
                    //draws ONE rectangle if there is remaining amount & fits into remaining area (biggest to smallest)
                    else if (counter[j] < rect[j].quant && rect[j].y <= remainingRowArea.y && rect[j].x <= remainingRowArea.x)
                    {
                        g.DrawRectangle(rect[j].pen, Convert.ToInt32(topLeftCoord.x * 10), Convert.ToInt32(topLeftCoord.y * 10), Convert.ToInt32(rect[j].x * 10), Convert.ToInt32(rect[j].y * 10));
                        topLeftCoord.y     += rect[j].y;
                        remainingRowArea.y -= rect[j].y;
                        counter[j]++;
                        if (rect[j].x > nextRowx)
                        {
                            nextRowx = rect[j].x;
                        }
                        Debug.Print("Instance {0} - Drew new " + rect[j].penColor.ToKnownColor() + " rectangle, #{1} \n", i, counter[j]);
                        break;
                    }
                    else
                    {
                        Debug.Print("Instance {0} - " + rect[j].penColor.ToKnownColor() + " Rectangle did not pass conditions", i);

                        //See if reached end of sheet
                        if (j == rect.Length - 1)
                        {
                            endofSheet = true;
                        }
                    }
                }
                if (i == quantAll - 1)
                {
                    Debug.Print("Completed. Final instance: {0}", i);
                }
            }

            //print and save last sheet
            bmp.Save(savePath + "Sheet-" + sheetNum + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            MessageBox.Show("Total number of sheets necessary: " + sheetNum, "Packing completed", MessageBoxButtons.OK);
            #endregion

            /* 4. clean up */
            xlWorksheet.Cells[7, 9].Value = sheetNum;
            topLeftCoord.x = 0;
            topLeftCoord.y = 0;
            rectList.Clear();
        }
    }
        public override void DrawItem(Graphics g, ImageListViewItem item, ItemState state, Rectangle bounds)
        {
            Clip = false;

            Size itemPadding = new Size(4, 4);
            Rectangle imageBounds = bounds;

            string text = Path.GetFileNameWithoutExtension(item.Text);
            Size szt = TextRenderer.MeasureText(text, ImageListView.Font);
            int textWidth = szt.Width + (itemPadding.Width * 2);

            if ((state & ItemState.Hovered) != ItemState.None && textWidth > bounds.Width)
            {
                bounds = new Rectangle(bounds.X + (bounds.Width / 2) - (textWidth / 2), bounds.Y, textWidth, bounds.Height);
            }

            // Paint background
            if (ImageListView.Enabled)
            {
                using (Brush bItemBack = new SolidBrush(ImageListView.Colors.BackColor))
                {
                    g.FillRectangle(bItemBack, bounds);
                }
            }
            else
            {
                using (Brush bItemBack = new SolidBrush(ImageListView.Colors.DisabledBackColor))
                {
                    g.FillRectangle(bItemBack, bounds);
                }
            }

            if ((state & ItemState.Disabled) != ItemState.None) // Paint background Disabled
            {
                using (Brush bDisabled = new LinearGradientBrush(bounds.Offset(1), ImageListView.Colors.DisabledColor1, ImageListView.Colors.DisabledColor2, LinearGradientMode.Vertical))
                {
                    Utility.FillRoundedRectangle(g, bDisabled, bounds, 4);
                }
            }
            else if ((ImageListView.Focused && ((state & ItemState.Selected) != ItemState.None)) ||
                (!ImageListView.Focused && ((state & ItemState.Selected) != ItemState.None) && ((state & ItemState.Hovered) != ItemState.None))) // Paint background Selected
            {
                using (Brush bSelected = new LinearGradientBrush(bounds.Offset(1), ImageListView.Colors.SelectedColor1, ImageListView.Colors.SelectedColor2, LinearGradientMode.Vertical))
                {
                    Utility.FillRoundedRectangle(g, bSelected, bounds, 4);
                }
            }
            else if (!ImageListView.Focused && ((state & ItemState.Selected) != ItemState.None)) // Paint background unfocused
            {
                using (Brush bGray64 = new LinearGradientBrush(bounds.Offset(1), ImageListView.Colors.UnFocusedColor1, ImageListView.Colors.UnFocusedColor2, LinearGradientMode.Vertical))
                {
                    Utility.FillRoundedRectangle(g, bGray64, bounds, 4);
                }
            }

            // Paint background Hovered
            if ((state & ItemState.Hovered) != ItemState.None)
            {
                using (Brush bHovered = new LinearGradientBrush(bounds.Offset(1), ImageListView.Colors.HoverColor1, ImageListView.Colors.HoverColor2, LinearGradientMode.Vertical))
                {
                    Utility.FillRoundedRectangle(g, bHovered, bounds, 4);
                }
            }

            // Draw the image
            Image img = item.GetCachedImage(CachedImageType.Thumbnail);
            if (img != null)
            {
                Rectangle pos = Utility.GetSizedImageBounds(img, new Rectangle(imageBounds.Location + itemPadding, ImageListView.ThumbnailSize));
                g.DrawImage(img, pos);
            }

            // Draw item text
            Color foreColor = ImageListView.Colors.ForeColor;
            if ((state & ItemState.Disabled) != ItemState.None)
            {
                foreColor = ImageListView.Colors.DisabledForeColor;
            }
            else if ((state & ItemState.Selected) != ItemState.None)
            {
                if (ImageListView.Focused)
                {
                    foreColor = ImageListView.Colors.SelectedForeColor;
                }
                else
                {
                    foreColor = ImageListView.Colors.UnFocusedForeColor;
                }
            }

            Rectangle rt = new Rectangle(bounds.Left, bounds.Top + (2 * itemPadding.Height) + ImageListView.ThumbnailSize.Height, bounds.Width, szt.Height);
            TextFormatFlags flags;

            if ((state & ItemState.Hovered) != ItemState.None)
            {
                flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoClipping;
            }
            else
            {
                flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.WordEllipsis;
            }

            TextRenderer.DrawText(g, text, ImageListView.Font, rt, foreColor, flags);
        }
Example #42
0
        /// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="fontname">字体</param>
        /// <param name="fontsize">字体大小</param>
        public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            byte[] _ImageBytes = File.ReadAllBytes(WebHelper.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = WebHelper.GetMapPath(filename);

            Graphics g        = Graphics.FromImage(img);
            Font     drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF    crSize;

            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (float)img.Width * (float).01;
                ypos = (float)img.Height * (float).01;
                break;

            case 2:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = (float)img.Height * (float).01;
                break;

            case 3:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = (float)img.Height * (float).01;
                break;

            case 4:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 5:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 6:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 7:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 8:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 9:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
        }
        //static StringFormat centerTipFormat = CreateTipStringFormat();

        public static Size GetTipSize(Control control, Graphics graphics, Font font, string description)
        {
            return(GetTipSize(control, graphics, new TipText(graphics, font, description)));
        }
Example #44
0
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.TextRenderingHint = TextRenderingHint.AntiAlias;
            //g.Clear(base.BackColor);

            switch (State)
            {
            case PushButtonState.Default:
                if (_normalImg != null)
                {
                    if (_toogle && _checked)
                    {
                        if (_downImg != null)
                        {
                            g.DrawImage(_downImg, base.ClientRectangle, new Rectangle(0, 0, _downImg.Width, _downImg.Height), GraphicsUnit.Pixel);
                        }
                    }
                    else
                    {
                        g.DrawImage(_normalImg, base.ClientRectangle, new Rectangle(0, 0, _normalImg.Width, _normalImg.Height), GraphicsUnit.Pixel);
                    }
                }
                break;

            case PushButtonState.Normal:
                if (_hoverImg != null)
                {
                    if (_toogle && _checked)
                    {
                        if (_downImg != null)
                        {
                            g.DrawImage(_downImg, base.ClientRectangle, new Rectangle(0, 0, _downImg.Width, _downImg.Height), GraphicsUnit.Pixel);
                        }
                    }
                    else
                    {
                        g.DrawImage(_hoverImg, base.ClientRectangle, new Rectangle(0, 0, _hoverImg.Width, _hoverImg.Height), GraphicsUnit.Pixel);
                    }
                }
                else
                {
                    if (_normalImg != null)
                    {
                        if (_toogle && _checked)
                        {
                            if (_downImg != null)
                            {
                                g.DrawImage(_downImg, base.ClientRectangle, new Rectangle(0, 0, _downImg.Width, _downImg.Height), GraphicsUnit.Pixel);
                            }
                        }
                        else
                        {
                            g.DrawImage(_normalImg, base.ClientRectangle, new Rectangle(0, 0, _normalImg.Width, _normalImg.Height), GraphicsUnit.Pixel);
                        }
                    }
                }
                break;

            case PushButtonState.Pressed:
                if (_downImg != null)
                {
                    g.DrawImage(_downImg, base.ClientRectangle, new Rectangle(0, 0, _downImg.Width, _downImg.Height), GraphicsUnit.Pixel);
                }
                else
                {
                    if (_normalImg != null)
                    {
                        g.DrawImage(_normalImg, base.ClientRectangle, new Rectangle(0, 0, _normalImg.Width, _normalImg.Height), GraphicsUnit.Pixel);
                    }
                }
                break;
            }

            Rectangle bounds    = base.ClientRectangle;
            PointF    textPoint = new PointF();
            SizeF     textSize  = TextRenderer.MeasureText(this.Text, this.Font);

            textPoint.X
                = bounds.X + (bounds.Width - textSize.Width) / 2 - _textLeft;
            textPoint.Y
                = (bounds.Bottom - textSize.Height) / 2 - _textTop;

            // Draw highlights
            float highlight_x = textPoint.X + _del_X;
            float highlight_y = textPoint.Y + _del_Y;
            //g.DrawString(
            //    this.Text,
            //    this.Font,
            //    new SolidBrush(_highLight),    // 高光颜色
            //    highlight_x,
            //    highlight_y);
            TextShadow tShadow = new TextShadow();

            tShadow.Draw(g, this.Text, this.Font, new PointF(textPoint.X, textPoint.Y));//文字阴影

            // 绘制正常文字
            //textPoint.X -= _del_X;
            //textPoint.Y -= _del_Y;
            g.DrawString(
                this.Text,
                this.Font,
                new SolidBrush(_textColor),    // 正常颜色
                textPoint.X,
                textPoint.Y);
        }
        /// <summary>
        /// Tooltip window proc
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="iMsg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        protected int WindowProc(IntPtr hWnd, UInt32 iMsg, IntPtr wParam, IntPtr lParam)
        {
            int height = 0;
            int width = 0;

            IntPtr nativeProc = WINAPI.GetProp(hWnd, "NATIVEPROC");

            if (iMsg == WINAPI.WM_PAINT)
            {
                // Drow the original tooltip
                int liWinProcResult = WINAPI.CallWindowProc(nativeProc, hWnd, iMsg, wParam, lParam);

                WINAPI.TOOLINFO ti = new WINAPI.TOOLINFO();
                ti.cbSize = Marshal.SizeOf(ti.GetType());
                ti.hwnd = GetHandler(moNotifyIcon);

                if (ti.hwnd != IntPtr.Zero)
                {
                    // Create graphics object for the tooltip
                    Graphics loGraphics = Graphics.FromHwnd(hWnd);

                    WINAPI.RECT rect = new WINAPI.RECT();
                    WINAPI.RECT rect1 = new WINAPI.RECT();

                    WINAPI.GetWindowRect(hWnd, ref rect);

                    // In rect1 - tooltip rectangle
                    // Calculate text display rectangle to rect
                    rect1 = rect;
                    WINAPI.SendMessage(hWnd, WINAPI.TTM_ADJUSTRECT, 0, out rect);

                    // Width and heigth of the text area
                    width = rect.right - rect.left;
                    height = rect.bottom - rect.top;

                    //Calculate iner rectangle of the text area
                    rect.left = rect.left - rect1.left;
                    rect.top = rect.top - rect1.top;
                    rect.right = rect.left + width;
                    rect.bottom = rect.top + height;

                    //Clear text area: 16 pixs - header, 30 pixs from bottom
                    loGraphics.FillRectangle(new SolidBrush(Color.LightYellow), new Rectangle(rect.left, rect.top + 16, width, height-30));

                    //Add close button and click handler
                    // 16 pixs for the button control
                    moCloseButton.Location = new System.Drawing.Point(rect.right - 16, rect.top);
                    moCloseButton.AutoSize = false;
                    moCloseButton.Click += CloseButtonClick;

                    WINAPI.SetParent(moCloseButton.Handle, hWnd);

                    //Adding panel to the tooltip below the header
                    moPanel.Location = new Point(rect.left, rect.top + 16);
                    WINAPI.SetParent(moPanel.Handle, hWnd);

                    loGraphics = null;

                }

                return liWinProcResult;
            }


            return WINAPI.CallWindowProc(nativeProc, hWnd, iMsg, wParam, lParam);
        }
Example #46
0
        public SimBuffer_Angle(Simulation sim, Vector2[] particleUV, int width, int height)
        {
            this.sim = sim;
            int angleNum = sim.numberOfAngleConstraints();
            int parNum   = sim.numberOfParticles();

            //angle uv
            float usage = 0f;

            if (!SimBuffer.GetTexDimension(angleNum, out deltaRTWidth, out deltaRTHeight, out usage))
            {
                Debug.LogError("Cannot create SimBuffer Angle deltaw rt with wrong dimesnion!");
                return;
            }
            angleUV = new Vector2[angleNum];
            int   count = 0;
            float halfW = 0.5f / deltaRTWidth;
            float halfH = 0.5f / deltaRTHeight;

            for (int y = 0; y < deltaRTHeight; y++)
            {
                for (int x = 0; x < deltaRTWidth; x++)
                {
                    if (count < angleNum)
                    {
                        angleUV[count] = new Vector2((float)x / (float)deltaRTWidth + halfW, (float)y / (float)deltaRTHeight + halfH);
                    }
                    count++;
                }
            }

            tempRT      = new RenderTexture[sim.maxAngleConvergenceID - 1];
            tempDeltaRT = new RenderTexture[sim.maxAngleConvergenceID];
            paramRT     = new RenderTexture[sim.maxAngleConvergenceID];
            deltaMesh   = new Mesh[sim.maxAngleConvergenceID];

            ID_AngleParamRT  = Shader.PropertyToID("_AngleParamRT");
            ID_AngleConstant = Shader.PropertyToID("_AngleConstant");
            ID_PositionRT    = Shader.PropertyToID("_PositionRT");
            ID_AngleDeltaRT  = Shader.PropertyToID("_AngleDeltaRT");

            //rg = the other end point's uv, ba = uv in the delta rt
            Color[]   paramRTColor = new Color[width * height];
            Texture2D tempTex      = new Texture2D(width, height, TextureFormat.RGBAFloat, false, false);

            for (int i = 0; i < sim.maxAngleConvergenceID; i++)
            {
                //delta mesh
                int agbyid = sim.numberOfAnglesByConvID(i + 1);
                deltaMesh[i] = SimBuffer.PointMesh(agbyid);
                List <Vector3> vtc = new List <Vector3> (agbyid);         //xy = a uv,y=fixedangle
                List <Color>   cl  = new List <Color> (agbyid);           //rg=b uv,ba = m uv;
                List <Vector2> uv  = new List <Vector2> (agbyid);         //delta rt uv;

                //init rt
                paramRT[i] = new RenderTexture(width, height, 0, RTFormat.ARGB);
                paramRT[i].Create();

                //prepare temp color
                for (int k = 0; k < width * height; k++)
                {
                    if (k < parNum)
                    {
                        Vector2 puv = particleUV[k];
                        paramRTColor[k] = new Color(puv.x, puv.y, 0f, 0f);                      //rg = other end,ba = uv in deltart
                    }
                    else
                    {
                        paramRTColor[k] = Color.clear;
                    }
                }

                //get info
                for (int j = 0; j < angleNum; j++)
                {
                    AngleConstraint2D ag = sim.getAngleConstraint(j);
                    if (ag.convergenceGroupID == i + 1)
                    {
                        int a      = sim.getParticleIndex(ag.ParticleB);
                        int b      = sim.getParticleIndex(ag.ParticleM);
                        int aIndex = sim.getParticleIndex(ag.ParticleA);
                        //if it's free, rg = the other end's uv, else = own uv
                        if (ag.ParticleB.IsFree)
                        {
                            paramRTColor[a].r = particleUV[b].x;
                            paramRTColor[a].g = particleUV[b].y;
                        }
                        if (ag.ParticleM.IsFree)
                        {
                            paramRTColor[b].r = particleUV[a].x;
                            paramRTColor[b].g = particleUV[a].y;
                        }
                        paramRTColor[a].b = paramRTColor[b].b = angleUV[j].x;
                        paramRTColor[a].a = paramRTColor[b].a = angleUV[j].y;

                        //mesh vtc and cl
                        vtc.Add(new Vector3(angleUV[j].x, angleUV[j].y, ag.angle_Fixed));
                        uv.Add(particleUV[aIndex]);
                        cl.Add(new Color(particleUV[a].x, particleUV[a].y, particleUV[b].x, particleUV[b].y));
                    }
                }

                //blit
                tempTex.SetPixels(paramRTColor);
                tempTex.Apply();
                Graphics.Blit(tempTex, paramRT[i]);

                //delta mesh
                deltaMesh[i].vertices = vtc.ToArray();
                deltaMesh[i].colors   = cl.ToArray();
                deltaMesh[i].uv       = uv.ToArray();
                //deltaMesh[i].UploadMeshData(true);
            }

            Extension.ObjDestroy(tempTex);

            //mpb
            mpb = new MaterialPropertyBlock[sim.maxSpringConvergenceID];
            for (int i = 0; i < sim.maxAngleConvergenceID; i++)
            {
                mpb[i] = new MaterialPropertyBlock();
                mpb[i].SetTexture(ID_AngleParamRT, paramRT[i]);
                mpb[i].SetFloat(ID_AngleConstant, sim.Settings.angleConstant);
            }
        }
        private void preProcessIcons()
        {
            // pre-process and pre-allocate texture brushes (icons)
            if (_baseTabControl == null || _baseTabControl.TabCount == 0 || _baseTabControl.ImageList == null || _tabRects == null || _tabRects.Count == 0)
                return;

            // Calculate lightness and color
            float l = UseColors ? SkinManager.ColorScheme.TextColor.R / 255 : SkinManager.Theme == MaterialSkinManager.Themes.LIGHT ? 0f : 1f;
            float r = (_highlightWithAccent ? SkinManager.ColorScheme.AccentColor.R : SkinManager.ColorScheme.PrimaryColor.R) / 255f;
            float g = (_highlightWithAccent ? SkinManager.ColorScheme.AccentColor.G : SkinManager.ColorScheme.PrimaryColor.G) / 255f;
            float b = (_highlightWithAccent ? SkinManager.ColorScheme.AccentColor.B : SkinManager.ColorScheme.PrimaryColor.B) / 255f;

            // Create matrices
            float[][] matrixGray = {
                    new float[] {   0,   0,   0,   0,  0}, // Red scale factor
                    new float[] {   0,   0,   0,   0,  0}, // Green scale factor
                    new float[] {   0,   0,   0,   0,  0}, // Blue scale factor
                    new float[] {   0,   0,   0, .7f,  0}, // alpha scale factor
                    new float[] {   l,   l,   l,   0,  1}};// offset

            float[][] matrixColor = {
                    new float[] {   0,   0,   0,   0,  0}, // Red scale factor
                    new float[] {   0,   0,   0,   0,  0}, // Green scale factor
                    new float[] {   0,   0,   0,   0,  0}, // Blue scale factor
                    new float[] {   0,   0,   0,   1,  0}, // alpha scale factor
                    new float[] {   r,   g,   b,   0,  1}};// offset

            ColorMatrix colorMatrixGray = new ColorMatrix(matrixGray);
            ColorMatrix colorMatrixColor = new ColorMatrix(matrixColor);

            ImageAttributes grayImageAttributes = new ImageAttributes();
            ImageAttributes colorImageAttributes = new ImageAttributes();

            // Set color matrices
            grayImageAttributes.SetColorMatrix(colorMatrixGray, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            colorImageAttributes.SetColorMatrix(colorMatrixColor, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            // Create brushes
            iconsBrushes = new Dictionary<string, TextureBrush>(_baseTabControl.TabPages.Count);
            iconsSelectedBrushes = new Dictionary<string, TextureBrush>(_baseTabControl.TabPages.Count);
            iconsSize = new Dictionary<string, Rectangle>(_baseTabControl.TabPages.Count);

            foreach (TabPage tabPage in _baseTabControl.TabPages)
            {
                // skip items without image
                if (String.IsNullOrEmpty(tabPage.ImageKey) || _tabRects == null)
                    continue;

                // Image Rect
                Rectangle destRect = new Rectangle(0, 0, _baseTabControl.ImageList.Images[tabPage.ImageKey].Width, _baseTabControl.ImageList.Images[tabPage.ImageKey].Height);

                // Create a pre-processed copy of the image (GRAY)
                Bitmap bgray = new Bitmap(destRect.Width, destRect.Height);
                using (Graphics gGray = Graphics.FromImage(bgray))
                {
                    gGray.DrawImage(_baseTabControl.ImageList.Images[tabPage.ImageKey],
                        new Point[] {
                                new Point(0, 0),
                                new Point(destRect.Width, 0),
                                new Point(0, destRect.Height),
                        },
                        destRect, GraphicsUnit.Pixel, grayImageAttributes);
                }

                // Create a pre-processed copy of the image (PRIMARY COLOR)
                Bitmap bcolor = new Bitmap(destRect.Width, destRect.Height);
                using (Graphics gColor = Graphics.FromImage(bcolor))
                {
                    gColor.DrawImage(_baseTabControl.ImageList.Images[tabPage.ImageKey],
                        new Point[] {
                                new Point(0, 0),
                                new Point(destRect.Width, 0),
                                new Point(0, destRect.Height),
                        },
                        destRect, GraphicsUnit.Pixel, colorImageAttributes);
                }

                // added processed image to brush for drawing
                TextureBrush textureBrushGray = new TextureBrush(bgray);
                TextureBrush textureBrushColor = new TextureBrush(bcolor);

                textureBrushGray.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;
                textureBrushColor.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;

                // Translate the brushes to the correct positions
                var currentTabIndex = _baseTabControl.TabPages.IndexOf(tabPage);

                Rectangle iconRect = new Rectangle(
                   _tabRects[currentTabIndex].X + (tabHeight / 2) - (_baseTabControl.ImageList.Images[tabPage.ImageKey].Width / 2),
                   _tabRects[currentTabIndex].Y + (tabHeight / 2) - (_baseTabControl.ImageList.Images[tabPage.ImageKey].Height / 2),
                   _baseTabControl.ImageList.Images[tabPage.ImageKey].Width, _baseTabControl.ImageList.Images[tabPage.ImageKey].Height);

                textureBrushGray.TranslateTransform(iconRect.X + iconRect.Width / 2 - _baseTabControl.ImageList.Images[tabPage.ImageKey].Width / 2, iconRect.Y + iconRect.Height / 2 - _baseTabControl.ImageList.Images[tabPage.ImageKey].Height / 2);
                textureBrushColor.TranslateTransform(iconRect.X + iconRect.Width / 2 - _baseTabControl.ImageList.Images[tabPage.ImageKey].Width / 2, iconRect.Y + iconRect.Height / 2 - _baseTabControl.ImageList.Images[tabPage.ImageKey].Height / 2);

                // add to dictionary
                iconsBrushes.Add(tabPage.ImageKey, textureBrushGray);
                iconsSelectedBrushes.Add(tabPage.ImageKey, textureBrushColor);
                iconsSize.Add(tabPage.ImageKey, new Rectangle(0, 0, iconRect.Width, iconRect.Height));
            }
        }
Example #48
0
        private void SaveButtonImage(int id)
        {
            if (Slots[id - 1] == null || Storage.GetSlotById(id) == null) return;

            string filename_0 = Storage.GetSlotById(id).Image_0;
            string filename_1 = Storage.GetSlotById(id).Image_1;
            string baseName = Storage.CurPathString();
            if (baseName != "") baseName += ".";
            string saveName_0 = baseName + id.ToString() + "_0.png";
            string saveName_1 = baseName + id.ToString() + "_1.png";

            try
            {
                Bitmap slotImage_0 = Bitmap.FromFile(filename_0) as Bitmap;
                Graphics g = Graphics.FromImage(slotImage_0);
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                SlotLabel label = Slots[id - 1].Controls.OfType<SlotLabel>().First();
                if (label != null)
                {
                    Bitmap label_bmp = new Bitmap(label.Width, label.Height);
                    label.DrawToBitmap(label_bmp, new Rectangle(0, 0, label.Width, label.Height));
                    g.CompositingMode = CompositingMode.SourceOver;
                    g.DrawImage(label_bmp, new Rectangle(0, 0, label.Width, label.Height));
                }

                string save = Storage.ButtonsDir + "\\" + saveName_0;
                if (File.Exists(save)) File.Delete(save);
                slotImage_0.Save(save);

                g.Flush();

                Bitmap slotImage_1 = new Bitmap(70,70);
                g = Graphics.FromImage(slotImage_1);
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;

                ActionSlot sl = new ActionSlot();
                sl = Slots[id - 1].Clone();
                sl.BackgroundImage = Image.FromFile(filename_1);
                //label = sl.Controls.OfType<SlotLabel>().First();
                SlotLabel l = label.Clone();
                l.Parent = sl;
                foreach(Control c in sl.Controls)
                {
                    Console.WriteLine("!");
                }
                //label = sl.Controls.OfType<SlotLabel>().First();
                //sl.DrawToBitmap(slotImage_1, new Rectangle(0, 0, sl.Width, sl.Height));
                //g.DrawImage(slotImage_1, new Rectangle(0, 0, slotImage_1.Width, slotImage_1.Height));
                if (l != null)
                {
                    Bitmap label_bmp = new Bitmap(label.Width, label.Height);
                    l.DrawToBitmap(label_bmp, new Rectangle(0, 0, label.Width, label.Height));
                    g.CompositingMode = CompositingMode.SourceOver;
                    g.DrawImage(label_bmp, new Rectangle(0, 0, label.Width, label.Height));
                }

                save = Storage.ButtonsDir + "\\" + saveName_1;
                if (File.Exists(save)) File.Delete(save);
                slotImage_1.Save(save);
            }
            catch(Exception err)
            {
                Console.WriteLine(err);
            }
        }
Example #49
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="graphics">绘图对象</param>
 /// <param name="newMode">新像素偏移模式</param>
 public PixelOffsetModeGraphics(Graphics graphics, PixelOffsetMode newMode)
 {
     this.m_Graphics          = graphics;
     this.m_OldMode           = graphics.PixelOffsetMode;
     graphics.PixelOffsetMode = newMode;
 }
Example #50
0
		private void Init (Bitmap bitmap) {
			_bitmap = bitmap;
			_graphics = Graphics.FromImage (_bitmap);
		}
Example #51
0
        private static void DrawPolyLineImpl(Graphics g, Color color, Point[] points)
        {
            if (points.Length < 1)
            {
                return;
            }

            var nativeColor = (uint)(color.R + (color.G << 8) + (color.B << 16));

            IntPtr hdc       = IntPtr.Zero;
            IntPtr pen       = IntPtr.Zero;
            IntPtr oldObject = IntPtr.Zero;

            try
            {
                hdc = g.GetHdc();
                pen = SafeNativeMethods.CreatePen(NativeConstants.PS_SOLID, 1, nativeColor);

                if (pen == IntPtr.Zero)
                {
                    NativeMethods.ThrowOnWin32Error("CreatePen returned NULL");
                }

                oldObject = SafeNativeMethods.SelectObject(hdc, pen);

                NativeStructs.POINT pt;
                bool bResult = SafeNativeMethods.MoveToEx(hdc, points[0].X, points[0].Y, out pt);

                if (!bResult)
                {
                    NativeMethods.ThrowOnWin32Error("MoveToEx returned false");
                }

                for (int i = 1; i < points.Length; ++i)
                {
                    bResult = SafeNativeMethods.LineTo(hdc, points[i].X, points[i].Y);

                    if (!bResult)
                    {
                        NativeMethods.ThrowOnWin32Error("LineTo returned false");
                    }
                }
            }

            finally
            {
                if (oldObject != IntPtr.Zero)
                {
                    SafeNativeMethods.SelectObject(hdc, oldObject);
                    oldObject = IntPtr.Zero;
                }

                if (pen != IntPtr.Zero)
                {
                    SafeNativeMethods.DeleteObject(pen);
                    pen = IntPtr.Zero;
                }

                if (hdc != IntPtr.Zero)
                {
                    g.ReleaseHdc(hdc);
                    hdc = IntPtr.Zero;
                }
            }

            GC.KeepAlive(g);
        }
Example #52
0
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            SizeF    tamañoTexto = new SizeF();
            Graphics graphics    = ev.Graphics;

            int indexSector;

            try
            {
                if (!buffer.EmptyListFormato())
                {
                    if (!buffer.IsModeRead)
                    {
                        buffer.SiguienteFormato();
                        buffer.SiguientePagina();
                        buffer.IsModeRead = true;
                    }

                    for (indexSector = 1; indexSector < 5; indexSector++)
                    {
                        FormatoImpresion formato = buffer.GetFormato();
                        sector.ActualizarPosicion(indexSector);
                        PaintCabecera(formato.Cabecera, graphics, this.sector);

                        FormatoImpresionPagina pagina = buffer.GetPagina();
                        do
                        {
                            if (buffer.SiguienteLinea())
                            {
                                buffer.IsModeRead = true;
                                FormatoImpresionPaginaLinea linea = buffer.GetLinea();
                                switch (linea.TipoLinea)
                                {
                                case FormatoImpresionPaginaLinea.TipoPaginaLinea.TituloArea:
                                    tamañoTexto = graphics.MeasureString(linea.Nombre, EstiloFuentePagina.TituloArea);
                                    graphics.DrawString(linea.Nombre, EstiloFuentePagina.TituloArea, Brushes.Black, (this.sector.Inicio.X + this.sector.Limite.X) / 2 - tamañoTexto.Width / 2 + this.sector.Configuracion.Margen.Left, this.sector.Cabezal);
                                    tamañoTexto.Height += 5;    //TITULO DE LABORATORIO
                                    break;

                                case FormatoImpresionPaginaLinea.TipoPaginaLinea.TituloExamen:
                                    graphics.DrawString(linea.Nombre, EstiloFuentePagina.TituloExamen, Brushes.Black, this.sector.Inicio.X + this.sector.Configuracion.Margen.Left, this.sector.Cabezal);    //TITULO DEL EXAMEN
                                    tamañoTexto = graphics.MeasureString(linea.Nombre, EstiloFuentePagina.TituloExamen);
                                    break;

                                case FormatoImpresionPaginaLinea.TipoPaginaLinea.ItemSimple:
                                    graphics.DrawString(linea.Nombre + ":  " + linea.Resultado, EstiloFuentePagina.Item, Brushes.Black, this.sector.Inicio.X + this.sector.Configuracion.Margen.Left * 2, this.sector.Cabezal);
                                    tamañoTexto = graphics.MeasureString(linea.Nombre, EstiloFuentePagina.Item);
                                    break;

                                case FormatoImpresionPaginaLinea.TipoPaginaLinea.ItemTexto:
                                    graphics.DrawString(linea.Resultado, EstiloFuentePagina.Item, Brushes.Black, this.sector.Inicio.X + this.sector.Configuracion.Margen.Left * 2, this.sector.Cabezal);
                                    tamañoTexto = graphics.MeasureString(linea.Resultado, EstiloFuentePagina.Item);
                                    break;

                                case FormatoImpresionPaginaLinea.TipoPaginaLinea.TituloGrupo:
                                    graphics.DrawString(linea.Nombre + ":  ", EstiloFuentePagina.TituloGrupo, Brushes.Black, this.sector.Inicio.X + this.sector.Configuracion.Margen.Left, this.sector.Cabezal);

                                    tamañoTexto = graphics.MeasureString(linea.Nombre, EstiloFuentePagina.TituloGrupo);
                                    break;
                                }
                                this.sector.Cabezal += ((int)tamañoTexto.Height + this.sector.Configuracion.Sangria);
                            }
                            else
                            {
                                buffer.IsModeRead = false;
                                if (!buffer.SiguientePagina())
                                {
                                    if (!buffer.SiguienteFormato())
                                    {
                                        indexSector = 5;
                                        break;
                                    }
                                    else
                                    {
                                        buffer.SiguientePagina();
                                        buffer.IsModeRead = true;
                                        break;
                                    }
                                }
                                else
                                {
                                    buffer.IsModeRead = true;
                                    break;
                                }
                            }
                        }while (sector.SectorLlenable());
                    }
                }

                ev.HasMorePages = buffer.IsModeRead;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #53
0
        private void ResizeSelection(Point cursor, int width, int height)
        {
            //camera.Unlock();

            Graphics g = this.CreateGraphics();

            if (CurrentAction == ClickAction.LeftSizing)
            {
                if (cursor.X < CurrentBottomRight.X - 10)
                {
                    //Erase the previous rectangle
                    CurrentTopLeft.X = cursor.X;
                    RectangleWidth   = CurrentBottomRight.X - CurrentTopLeft.X;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.TopLeftSizing)
            {
                if (cursor.X < CurrentBottomRight.X - 10 && cursor.Y < CurrentBottomRight.Y - 10)
                {
                    //Erase the previous rectangle
                    CurrentTopLeft.X = cursor.X;
                    CurrentTopLeft.Y = cursor.Y;
                    RectangleWidth   = CurrentBottomRight.X - CurrentTopLeft.X;
                    RectangleHeight  = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.BottomLeftSizing)
            {
                if (cursor.X < CurrentBottomRight.X - 10 && cursor.Y > CurrentTopLeft.Y + 10)
                {
                    //Erase the previous rectangle
                    CurrentTopLeft.X     = cursor.X;
                    CurrentBottomRight.Y = cursor.Y;
                    RectangleWidth       = CurrentBottomRight.X - CurrentTopLeft.X;
                    RectangleHeight      = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.RightSizing)
            {
                if (cursor.X > CurrentTopLeft.X + 10)
                {
                    //Erase the previous rectangle
                    CurrentBottomRight.X = cursor.X;
                    RectangleWidth       = CurrentBottomRight.X - CurrentTopLeft.X;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.TopRightSizing)
            {
                if (cursor.X > CurrentTopLeft.X + 10 && cursor.Y < CurrentBottomRight.Y - 10)
                {
                    //Erase the previous rectangle
                    CurrentBottomRight.X = cursor.X;
                    CurrentTopLeft.Y     = cursor.Y;
                    RectangleWidth       = CurrentBottomRight.X - CurrentTopLeft.X;
                    RectangleHeight      = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.BottomRightSizing)
            {
                if (cursor.X > CurrentTopLeft.X + 10 && cursor.Y > CurrentTopLeft.Y + 10)
                {
                    //Erase the previous rectangle
                    CurrentBottomRight.X = cursor.X;
                    CurrentBottomRight.Y = cursor.Y;
                    RectangleWidth       = CurrentBottomRight.X - CurrentTopLeft.X;
                    RectangleHeight      = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.TopSizing)
            {
                if (cursor.Y < CurrentBottomRight.Y - 10)
                {
                    //Erase the previous rectangle
                    CurrentTopLeft.Y = cursor.Y;
                    RectangleHeight  = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
            if (CurrentAction == ClickAction.BottomSizing)
            {
                if (cursor.Y > CurrentTopLeft.Y + 10)
                {
                    //Erase the previous rectangle
                    CurrentBottomRight.Y = cursor.Y;
                    RectangleHeight      = CurrentBottomRight.Y - CurrentTopLeft.Y;
                    drawRect(CurrentTopLeft.X, CurrentTopLeft.Y, RectangleWidth, RectangleHeight);
                }
            }
        }
Example #54
0
        private Graphics m_Graphics;        //要修改像素偏移模式的绘图对象

        /// <summary>
        /// 构造函数,暂时修改为默认像素偏移
        /// </summary>
        /// <param name="graphics">绘图对象</param>
        public PixelOffsetModeGraphics(Graphics graphics)
            : this(graphics, PixelOffsetMode.Default)
        {
        }
Example #55
0
        // Paint control
        protected override void OnPaint(PaintEventArgs pe)
        {
            if ((needSizeUpdate) || (firstFrame))
            {
                UpdatePosition();
                needSizeUpdate = false;
            }

            // lock
            ///Monitor.Enter(this);

            Graphics  g   = pe.Graphics;
            Rectangle rc  = this.ClientRectangle;
            Pen       pen = new Pen(rectColor, 1);

            // draw rectangle
            //newcode

            if (imageToFrame)
            {
                rc.Width  = 320;
                rc.Height = 240;
            }
            //newcode


            g.DrawRectangle(pen, rc.X, rc.Y, rc.Width - 1, rc.Height - 1);

            //if (CameraRig.rig[CameraRig.activeCam].cam != null)
            if (camera != null)
            {
                try
                {
                    camera.Lock();

                    // draw frame
                    if (camera.pubFrame != null)
                    {
                        if (showCam)
                        {
                            //newcode
                            if (imageToFrame)
                            {
                                g.DrawRectangle(pen, camera.pubFrame.Width, camera.pubFrame.Height, rc.Width, rc.Height);
                                g.DrawImage(bubble.resizeImage(camera.pubFrame, 320, 240), rc.X + 1, rc.Y + 1, rc.Width - 2, rc.Height - 2);
                            }
                            else
                            {
                                g.DrawImage(camera.pubFrame, rc.X + 1, rc.Y + 1, rc.Width - 2, rc.Height - 2);
                            }
                            //newcode
                            firstFrame = false;
                        }
                    }
                    else
                    {
                        if (showCam)
                        {
                            // Create font and brush
                            Font       drawFont  = new Font("Arial", 12);
                            SolidBrush drawBrush = new SolidBrush(Color.White);

                            g.DrawString("Connecting ...", drawFont, drawBrush, new PointF(5, 5));

                            drawBrush.Dispose();
                            drawFont.Dispose();
                        }
                    }
                }
                catch (Exception)
                {
                    camera.Unlock();
                }
                finally
                {
                    camera.Unlock();
                }
            }

            pen.Dispose();

            // unlock
            //Monitor.Exit(this);
            base.OnPaint(pe);
        }
Example #56
0
        public FormBrowser(string serverUri, string browserUILanguage, Color browserBackColor)
        {
            ServerUri = serverUri;
            BrowserUILanguage = browserUILanguage;

            InitializeComponent();
            ToolMenu.Renderer = new ToolStripOverride();
            SizeAdjuster.BackColor = ToolMenu.BackColor = browserBackColor;
            switch (BrowserUILanguage) {
                case "zh":
                    ContextMenuTool_ShowToolMenu.Text = "显示工具条";
                    ToolMenu_Zoom.Text = "缩放";
                    ToolMenu_Mute.Text = "静音";
                    ToolMenu_Refresh.Text = "刷新";
                    ToolMenu_NavigateToLogInPage.Text = "转到登录页";
                    ToolMenu_Other.Text = "其它";
                    ToolMenu_Other_ScreenShot.Text = "截图(&S)";
                    ToolMenu_Other_LastScreenShot.Text = "最后一次截图(&P)";
                    ToolMenu_Other_LastScreenShot_OpenScreenShotFolder.Text = "打开截图文件夹(&O)";
                    ToolMenu_Other_LastScreenShot_CopyToClipboard.Text = "复制到剪贴板(&C)";
                    ToolMenu_Other_Zoom.Text = "缩放(&Z)";
                    ToolMenu_Other_Zoom_Current.Text = "当前";
                    ToolMenu_Other_Zoom_Fit.Text = "自适应";
                    ToolMenu_Other_Volume.Text = "音量(&V)";
                    ToolMenu_Other_Mute.Text = "静音(&M)";
                    ToolMenu_Other_Refresh.Text = "刷新(&R)";
                    ToolMenu_Other_NavigateToLogInPage.Text = "转到登录页(&L)";
                    ToolMenu_Other_Navigate.Text = "转到网址(&N)...";
                    ToolMenu_Other_OpenInNewWindow.Text = "在新窗口打开";
                    ToolMenu_Other_OpenInNewWindow_EnterUrl.Text = "输入网址...";
                    ToolMenu_Other_AppliesStyleSheet.Text = "应用样式表";
                    ToolMenu_Other_ClearCache.Text = "清除缓存";
                    ToolMenu_Other_Alignment.Text = "工具条位置(&A)";
                    ToolMenu_Other_Alignment_Top.Text = "上(&T)";
                    ToolMenu_Other_Alignment_Bottom.Text = "下(&B)";
                    ToolMenu_Other_Alignment_Left.Text = "左(&L)";
                    ToolMenu_Other_Alignment_Right.Text = "右(&R)";
                    ToolMenu_Other_Alignment_Invisible.Text = "隐藏(&I)";
                    ToolMenu_Other_ChromiumDevTools.Text = "Chromium 开发者工具(&D)";
                    break;
                default:
                    // Default UI language is Japanese
                    break;
            }

            _volumeManager = new VolumeManager((uint)System.Diagnostics.Process.GetCurrentProcess().Id);

            // 音量設定用コントロールの追加
            {
                var control = new NumericUpDown();
                control.Name = "ToolMenu_Other_Volume_VolumeControl";
                control.Maximum = 100;
                control.TextAlign = HorizontalAlignment.Right;
                control.Font = ToolMenu_Other_Volume.Font;
                control.ValueChanged += ToolMenu_Other_Volume_ValueChanged;
                control.Tag = false;
                var host = new ToolStripControlHost(control, "ToolMenu_Other_Volume_VolumeControlHost");
                control.Size = new Size(host.Width - control.Margin.Horizontal, host.Height - control.Margin.Vertical);
                control.Location = new Point(control.Margin.Left, control.Margin.Top);

                ToolMenu_Other_Volume.DropDownItems.Add(host);
            }

            // スクリーンショットプレビューコントロールの追加
            {
                double zoomrate = 0.25;
                var control = new PictureBox();
                control.Name = "ToolMenu_Other_LastScreenShot_Image";
                control.SizeMode = PictureBoxSizeMode.Zoom;
                control.Size = new Size((int)(KanColleSize.Width * zoomrate), (int)(KanColleSize.Height * zoomrate));
                control.Margin = new Padding();
                control.Image = new Bitmap((int)(KanColleSize.Width * zoomrate), (int)(KanColleSize.Height * zoomrate), PixelFormat.Format24bppRgb);
                using (var g = Graphics.FromImage(control.Image)) {
                    g.Clear(SystemColors.Control);
                    switch (BrowserUILanguage) {
                        case "zh":
                            g.DrawString("还没有截过图。", Font, Brushes.Black, new Point(4, 4));
                            break;
                        default:
                            g.DrawString("スクリーンショットをまだ撮影していません。", Font, Brushes.Black, new Point(4, 4));
                            break;
                    }
                }
                var host = new ToolStripControlHost(control, "ToolMenu_Other_LastScreenShot_ImageHost");
                host.Size = new Size(control.Width + control.Margin.Horizontal, control.Height + control.Margin.Vertical);
                host.AutoSize = false;
                control.Location = new Point(control.Margin.Left, control.Margin.Top);
                host.Click += ToolMenu_Other_LastScreenShot_ImageHost_Click;

                ToolMenu_Other_LastScreenShot.DropDownItems.Insert(0, host);
            }
        }
Example #57
0
        //Create a constructor (initialises the values of the fields)

        // Methods for the Planet class
        public void drawPlanet(Graphics g)
        {
            planetRec = new Rectangle(x, y, width, height);
            g.DrawImage(planetImage, planetRec);
        }
Example #58
0
        private void drawRect(int topLeftX, int topLeftY, int width, int height)
        {
            try
            {
                Graphics g = this.CreateGraphics();

                if (topLeftY + height > camera.pubFrame.Height)
                {
                    height = camera.pubFrame.Height - topLeftY;
                }
                if (height < 1)
                {
                    height = 1;
                }
                if (topLeftY < 0)
                {
                    topLeftY = 0;
                }

                if (topLeftY >= camera.pubFrame.Height)
                {
                    topLeftY = camera.pubFrame.Height - 1;
                    height   = 1;
                }


                if (topLeftX + width > camera.pubFrame.Width)
                {
                    width = camera.pubFrame.Width - topLeftX;
                }
                if (width < 1)
                {
                    width = 1;
                }
                if (topLeftX < 0)
                {
                    topLeftX = 0;
                }

                if (topLeftX >= camera.pubFrame.Width)
                {
                    topLeftX = camera.pubFrame.Width - 1;
                    width    = 1;
                }

                g.DrawRectangle(MyPen, topLeftX, topLeftY, width, height);
                g.Dispose();


                config.getProfile(bubble.profileInUse).rectX      = topLeftX;
                config.getProfile(bubble.profileInUse).rectY      = topLeftY;
                config.getProfile(bubble.profileInUse).rectWidth  = width;
                config.getProfile(bubble.profileInUse).rectHeight = height;

                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.rectX = topLeftX;
                CameraRig.updateInfo(bubble.profileInUse, CameraRig.ConnectedCameras[CameraRig.ConfigCam].cameraName, CameraRig.infoEnum.rectX, topLeftX);
                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.rectY = topLeftY;
                CameraRig.updateInfo(bubble.profileInUse, CameraRig.ConnectedCameras[CameraRig.ConfigCam].cameraName, CameraRig.infoEnum.rectY, topLeftY);
                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.rectWidth = width;
                CameraRig.updateInfo(bubble.profileInUse, CameraRig.ConnectedCameras[CameraRig.ConfigCam].cameraName, CameraRig.infoEnum.rectWidth, width);
                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.rectHeight = height;
                CameraRig.updateInfo(bubble.profileInUse, CameraRig.ConnectedCameras[CameraRig.ConfigCam].cameraName, CameraRig.infoEnum.rectHeight, height);

                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.Lock();
                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.MotionDetector.Reset();
                CameraRig.ConnectedCameras[CameraRig.ConfigCam].cam.Unlock();
            }
            catch { }
        }
Example #59
0
		public override void Render(Rectangle bounds, Graphics map) {
		}
        private void Paint_SimpleGph(object sender, PaintEventArgs e)
        {
            int y1, y2;
            Graphics g = e.Graphics;

            // Clipping the plygones start lines
            GraphicsPath path_clip1 = new GraphicsPath();
            path_clip1.AddPolygon(polyPoints_clip_small_gph_zone);
            Region region1 = new Region(path_clip1);            // Set the clipping region of the Graphics object.
            e.Graphics.SetClip(region1, CombineMode.Replace);

            Channel_Pen[0] = new Pen(Color.Brown); Channel_Pen[1] = new Pen(Color.Red);
            Channel_Pen[2] = new Pen(Color.Green); Channel_Pen[3] = new Pen(Color.Blue);
            Channel_Pen[4] = new Pen(Color.Magenta); Channel_Pen[5] = new Pen(Color.Black);

            Channel_Brush[0] = new SolidBrush(Color.Brown); Channel_Brush[1] = new SolidBrush(Color.Red);
            Channel_Brush[2] = new SolidBrush(Color.Green); Channel_Brush[3] = new SolidBrush(Color.Blue);
            Channel_Brush[4] = new SolidBrush(Color.Magenta); Channel_Brush[5] = new SolidBrush(Color.Black);

            Pen b1 = new Pen(Color.LightBlue);
            Pen b2 = new Pen(Color.LightGray);
            Pen b3 = new Pen(Color.DarkGray);
            Pen b4 = new Pen(Color.DarkBlue);
            Pen bx = b1;
            double val1;

            // Draw Up-Down buttons
            g.FillRectangle(b13Yellow, SimpleGph1_X0 + Up_button_dX-6, SimpleGph_Y0 + Up_button_dY-2, 35, 14);
            g.DrawString(" Up ", Font1bold, b0Black, SimpleGph1_X0 + Up_button_dX-4, SimpleGph_Y0 + Up_button_dY);
            g.FillRectangle(b10LightSalmon, SimpleGph1_X0 + Up_button_dX-6, SimpleGph_Y0 + Up_button_dY +18, 35, 15);
            g.DrawString("Down", Font1bold, b0Black, SimpleGph1_X0 + Up_button_dX-5, SimpleGph_Y0 + Up_button_dY + 20);

            // Draw graphics area
            g.DrawRectangle(b1, SimpleGph1_X0, SimpleGph_Y0-7,
                SimpleGph_dXlegend+SimpleGph_Y_width_MAX * 2 +160, SimpleGph_Y_width_MAX+14); // Draw the complete area 
            g.DrawRectangle(b1, SimpleGph1_X0+510, SimpleGph_Y0 - 7,
                SimpleGph_dXlegend + SimpleGph_Y_width_MAX * 2 + 160, SimpleGph_Y_width_MAX + 14); // Draw the complete area 
            // Graphics set 1 background
            g.FillRectangle(b1White, SimpleGph_dXlegend+SimpleGph1_X0, SimpleGph_Y0 - 5, SimpleGph_X_width_MAX, SimpleGph_Y_width_MAX+10);
            // Graphics set 2 background
            g.FillRectangle(b1White, SimpleGph_dXlegend+SimpleGph2_X0, SimpleGph_Y0 - 5, SimpleGph_X_width_MAX, SimpleGph_Y_width_MAX + 10);
            
            // drawing horisontal lines on the graphs
            for (int i1 = 0; i1 < 14; i1++)
            {
                if (i1 == 6) bx = b4; else bx = b2;

                // draw values on the vertical axis of powers
                val1 = SimpleGph1_P_max - (i1-1) * SimpleGph1_P_max/5;
                //if ((i1 % 2) == 1)
                    g.DrawString(val1.ToString(), Font0, b0Black, SimpleGph_dXlegend + SimpleGph1_X0 - 22, 
                        SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1 - 6) * 10 - 5);
                
                // draw values on the vertical axis of voltages
                val1 = 290 - i1 * 10;
                if((i1 % 2)==1) g.DrawString(val1.ToString(), Font0, b0Black, SimpleGph_dXlegend + SimpleGph2_X0-22, 
                    SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1 - 6) * 10 - 5);
                
                // graph of powers P
                g.DrawLine(bx, SimpleGph_dXlegend + SimpleGph1_X0, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1-6)*10,
                     SimpleGph_dXlegend + SimpleGph1_X0 + SimpleGph_X_width_MAX, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1 - 6) * 10);
                
                // graph of voltage level
                g.DrawLine(bx, SimpleGph_dXlegend + SimpleGph2_X0, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1 - 6) * 10,
                     SimpleGph_dXlegend + SimpleGph2_X0 + SimpleGph_X_width_MAX, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + (i1 - 6) * 10);
            }
            // draw vertical lines
            for (int i1 = 0; i1 < 7; i1++)
            {
                g.DrawLine(bx, SimpleGph_dXlegend + SimpleGph1_X0 + SimpleGph_X_width_MAX / 6 * i1 - step_w / 2, SimpleGph_Y0,
                     SimpleGph_dXlegend + SimpleGph1_X0 + SimpleGph_X_width_MAX / 6 * i1 - step_w / 2, SimpleGph_Y0 + SimpleGph_Y_width_MAX);
                g.DrawLine(bx, SimpleGph_dXlegend + SimpleGph2_X0 + SimpleGph_X_width_MAX/6*i1- step_w/2, SimpleGph_Y0,
                     SimpleGph_dXlegend + SimpleGph2_X0 + SimpleGph_X_width_MAX/6*i1 - step_w/2, SimpleGph_Y0 + SimpleGph_Y_width_MAX);
            }
            // display channels (the legend)
            for (int i1 = 0; i1 < 6; i1++)
            {
                g.DrawString(i1.ToString() +": "+ channel_name[i1], Font0, Channel_Brush[i1], SimpleGph1_X0 + 1, SimpleGph_Y0 + 12 * i1);
            }

            double power_factor = 1;
            if (graph_smallgph[0, graph_smallgph_PROP_P_fact] != "")
                power_factor = double.Parse(graph_smallgph[0, graph_smallgph_PROP_P_fact]);

            double voltage_factor = 1;
            if(graph_smallgph[0, graph_smallgph_PROP_U_fact] !="")
                voltage_factor = double.Parse(graph_smallgph[0, graph_smallgph_PROP_U_fact]);
            //double voltage_factor = voltage_level / 230;
            // draw graphics
            for (int ch=0; ch< SimpleGph_channels_MAX; ch++)
            for (int x1=0; x1< samples; x1++)
            {
                    // Graphics set 1
                y1 = -(int)Math.Round(SimpleGph_channels1[ch, x1]/ power_factor / SimpleGph1_P_max * 50); // we scale that P_max has only 50 pixels in the graph
                y2 = -(int)Math.Round(SimpleGph_channels1[ch, x1+1]/ power_factor / SimpleGph1_P_max * 50);
                if (x1 != 0) g.DrawLine(Channel_Pen[ch], SimpleGph_dXlegend+SimpleGph1_X0 + (x1-1)* step_w + step_w, SimpleGph_Y0 + SimpleGph_Y_width_MAX/2 + y1,
                    SimpleGph_dXlegend+SimpleGph1_X0 + (x1-1) * step_w + step_w, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2);
                g.DrawLine(Channel_Pen[ch], SimpleGph_dXlegend+SimpleGph1_X0 + (x1 - 1) * step_w + step_w, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2,
                    SimpleGph_dXlegend+SimpleGph1_X0 + x1 * step_w + step_w, SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2);

                    // Graphics set 2
                y1 = -(int)Math.Round(SimpleGph_channels2[ch, x1]/ voltage_factor - 230);
                y2 = -(int)Math.Round(SimpleGph_channels2[ch, x1 + 1] / voltage_factor - 230);
                if(x1!=0) g.DrawLine(Channel_Pen[ch], SimpleGph_dXlegend+SimpleGph2_X0 + (x1 - 1) * step_w+ step_w, 
                                                      SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y1,
                                                      SimpleGph_dXlegend+SimpleGph2_X0 + (x1 - 1) * step_w+ step_w, 
                                                      SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2);
                g.DrawLine(Channel_Pen[ch], SimpleGph_dXlegend+SimpleGph2_X0 + (x1 - 1) * step_w+ step_w, 
                                            SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2,
                                            SimpleGph_dXlegend+SimpleGph2_X0 + x1 * step_w+ step_w, 
                                            SimpleGph_Y0 + SimpleGph_Y_width_MAX / 2 + y2);
            }
        }