public static void Main(string[] args) { Graphics.DrawImageAbort imageCallback; Bitmap outbmp = new Bitmap (300, 300); Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver24bits.bmp"); Graphics dc = Graphics.FromImage (outbmp); ImageAttributes imageAttr = new ImageAttributes(); /* Simple image drawing */ dc.DrawImage(bmp, 0,0); /* Drawing using points */ PointF ulCorner = new PointF(150.0F, 0.0F); PointF urCorner = new PointF(350.0F, 0.0F); PointF llCorner = new PointF(200.0F, 150.0F); RectangleF srcRect = new Rectangle (0,0,100,100); PointF[] destPara = {ulCorner, urCorner, llCorner}; imageCallback = new Graphics.DrawImageAbort(DrawImageCallback); dc.DrawImage (bmp, destPara, srcRect, GraphicsUnit.Pixel, imageAttr, imageCallback); /* Using rectangles */ RectangleF destRect = new Rectangle (10,200,100,100); RectangleF srcRect2 = new Rectangle (50,50,100,100); dc.DrawImage (bmp, destRect, srcRect2, GraphicsUnit.Pixel); /* Simple image drawing with with scaling*/ dc.DrawImage(bmp, 200,200, 75, 75); outbmp.Save("drawimage.bmp", ImageFormat.Bmp); }
public static void WriteDefaultFaceCalculation(PointF[] shape) { var calculatedFaceAlignment = GetFaceCalculationsFromShape(shape); using (var db = new GrimacizerContext(GrimacizerContext.ConnectionString)) { var faceCalculations = db.FaceCalculations.FirstOrDefault(); faceCalculations._0_TamplaStanga = calculatedFaceAlignment._0_TamplaStanga; faceCalculations._1_TamplaDreapta = calculatedFaceAlignment._1_TamplaDreapta; faceCalculations._2_Barbie = calculatedFaceAlignment._2_Barbie; faceCalculations._3_SpranceanaDreapta = calculatedFaceAlignment._3_SpranceanaDreapta; faceCalculations._4_ArieOchiStang = calculatedFaceAlignment._4_ArieOchiStang; faceCalculations._5_ArieOchiDrept = calculatedFaceAlignment._5_ArieOchiDrept; faceCalculations._6_MarimeOchiStang = calculatedFaceAlignment._6_MarimeOchiStang; faceCalculations._7_MarimeOchiDrept = calculatedFaceAlignment._7_MarimeOchiDrept; faceCalculations._8_InaltimeGura = calculatedFaceAlignment._8_InaltimeGura; faceCalculations._9_Unghi_60_67 = calculatedFaceAlignment._9_Unghi_60_67; faceCalculations._10_Unghi_64_65 = calculatedFaceAlignment._10_Unghi_64_65; faceCalculations._11_LungimeGuraExterior = calculatedFaceAlignment._11_LungimeGuraExterior; faceCalculations._12_UnghiNasStanga = calculatedFaceAlignment._12_UnghiNasStanga; faceCalculations._13_UnghiNasDreapta = calculatedFaceAlignment._13_UnghiNasDreapta; faceCalculations._14_ArieFata = calculatedFaceAlignment._14_ArieFata; faceCalculations._15_ArieGura = calculatedFaceAlignment._15_ArieGura; db.SubmitChanges(); } }
public override bool Overlaps(RectangleShape rect, PointF offset) { // Two rectangles, A and B, overlap iff one of the corners of B is contained in A or if A is completely contained within B. PointF a1 = new PointF(-rect.Width / 2 + offset.X, -rect.Height / 2 + offset.Y); bool overlaps = (a1.X >= -width / 2) && (a1.X <= width / 2) && (a1.Y >= -height / 2) && (a1.Y <= height / 2); if (!overlaps) { PointF a2 = new PointF(rect.Width / 2 + offset.X, -rect.Height / 2 + offset.Y); overlaps = (a2.X >= -width / 2) && (a2.X <= width / 2) && (a2.Y >= -height / 2) && (a2.Y <= height / 2); if (!overlaps) { PointF a3 = new PointF(rect.Width / 2 + offset.X, rect.Height / 2 + offset.Y); overlaps = (a3.X >= -width / 2) && (a3.X <= width / 2) && (a3.Y >= -height / 2) && (a3.Y <= height / 2); if (!overlaps) { PointF a4 = new PointF(-rect.Width / 2 + offset.X, rect.Height / 2 + offset.Y); overlaps = (a4.X >= -width / 2) && (a4.X <= width / 2) && (a4.Y >= -height / 2) && (a4.Y <= height / 2); if (!overlaps) { overlaps = (-width / 2 >= a1.X) && (-width / 2 <= a2.X) && (-height / 2 >= a1.Y) && (-height / 2 <= a3.Y); } } } } return overlaps; }
public static float Angle(PointF pt1, PointF pt2) { if (pt1 == pt2) return 0.0F; else return (float) (Math.Atan2(pt2.Y - pt1.Y, pt2.X - pt1.X) * 360.0 / (Math.PI * 2)); }
/// <summary> /// Constructs a body adapter from a serialized version /// </summary> /// <param name="body"></param> public KinectBody(KGP.Serialization.Body.KinectBodyInternal body) { body.Validate(); //This will check preconditions to make sure we have a valid construct this.clippedEdges = body.ClippedEdges; this.handLeftConfidence = body.HandLeftConfidence; this.handLeftState = body.HandLeftState; this.handRightConfidence = body.HandRightConfidence; this.handRightState = body.HandRightState; this.isRestricted = body.IsRestricted; this.isTracked = body.IsTracked; Dictionary<JointType, JointOrientation> orientations = new Dictionary<JointType, JointOrientation>(); Dictionary<JointType, Joint> jointsDic = new Dictionary<JointType,Joint>(); for (int i = 0; i < body.Joints.Length;i++) { var joint = body.Joints[i]; orientations.Add(joint.JointType, body.JointOrientations[i]); jointsDic.Add(joint.JointType, joint); } this.joints = jointsDic; this.jointOrientations =orientations; this.lean = body.Lean; this.leanTrackingState = body.LeanTrackingState; this.trackingId = body.TrackingId; }
public static Point closestPointOfPolyline(Point[] polyline, Point pt) { PointF[] Ptsf = PointsToPointsF(polyline); PointF Ptf = PointToPointF (pt); double distanceClosest = Double.PositiveInfinity; PointF closestPoint = new PointF(); for(int x=0; x< Ptsf.Length-1; x++) { PointF closest; double dist = FindDistanceToSegment(Ptf, Ptsf[x], Ptsf[x+1], out closest); if(dist < distanceClosest) { distanceClosest = dist; closestPoint = closest; } } return PointFToPoint (closestPoint); }
public void NonDefaultConstructorTest(float x, float y) { PointF p1 = new PointF(x, y); Assert.Equal(x, p1.X); Assert.Equal(y, p1.Y); }
public DObject(PointF vpoint) { sx = 3; sy = 1; matrix = new double[3]; SetLine(0, vpoint.X, vpoint.Y, 1); }
public SimulationView (Context context, SensorManager sensorManager, IWindowManager window) : base (context) { Bounds = new PointF (); // Get an accelorometer sensor sensor_manager = sensorManager; accel_sensor = sensor_manager.GetDefaultSensor (SensorType.Accelerometer); // Calculate screen size and dpi var metrics = new DisplayMetrics (); window.DefaultDisplay.GetMetrics (metrics); meters_to_pixels_x = metrics.Xdpi / 0.0254f; meters_to_pixels_y = metrics.Ydpi / 0.0254f; // Rescale the ball so it's about 0.5 cm on screen var ball = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Ball); var dest_w = (int)(BALL_DIAMETER * meters_to_pixels_x + 0.5f); var dest_h = (int)(BALL_DIAMETER * meters_to_pixels_y + 0.5f); ball_bitmap = Bitmap.CreateScaledBitmap (ball, dest_w, dest_h, true); // Load the wood background texture var opts = new BitmapFactory.Options (); opts.InDither = true; opts.InPreferredConfig = Bitmap.Config.Rgb565; wood_bitmap = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Wood, opts); wood_bitmap2 = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Wood, opts); display = window.DefaultDisplay; particles = new ParticleSystem (this); }
// Constructors. public RectangleF(PointF location, SizeF size) { x = location.X; y = location.Y; width = size.Width; height = size.Height; }
/// <summary> /// Initializes a new instance of the <see cref="CustomBody"/> class. /// </summary> public CustomBody() { _clippedEdges = FrameEdges.None; _handLeftConfidence = TrackingConfidence.Low; _handLeftState = HandState.Unknown; _handRightConfidence = TrackingConfidence.Low; _handRightState = HandState.Unknown; _isDisposed = false; _isRestricted = false; _isTracked = false; _joints = new Dictionary<JointType, IJoint>(); _jointOrientations = new Dictionary<JointType, IJointOrientation>(); foreach (var jointType in CustomJointType.AllJoints) { _joints.Add(jointType, new CustomJoint(jointType)); _jointOrientations.Add(jointType, new CustomJointOrientation(jointType)); } _lean = new PointF(); _leanTrackingState = TrackingState.NotTracked; _trackingId = ulong.MaxValue; _hasMappedDepthPositions = false; _hasMappedColorPositions = false; }
private static PointF RotateAndFindNewDimensions(PointF point, float angle) { using (Matrix matrix = new Matrix()) { PointF[] points = new PointF[] { new PointF(0f, 0f), new PointF(0f, point.Y), new PointF(point.X, 0f), new PointF(point.X, point.Y) }; matrix.Rotate(angle); matrix.TransformPoints(points); float minX = points[0].X; float maxX = minX; float minY = points[0].Y; float maxY = minY; for (int i = 1; i < 4; i++) { minX = Math.Min(minX, points[i].X); maxX = Math.Max(maxX, points[i].X); minY = Math.Min(minY, points[i].Y); maxY = Math.Max(maxY, points[i].Y); } return new PointF(maxX - minX, maxY - minY); } }
public Bitmap generateTicket(string ticketType, string start, string destination, string price) { //Orte der verschiedenen Textboxen auf dem Ticket: Point StartLine1 = new Point(0,100); Point EndLine1 = new Point(960, 100); Point StartLine2 = new Point(0, 700); Point EndLine2 = new Point(960, 700); PointF logoLocation = new PointF(150,20); PointF fromLocation = new PointF(40,300); PointF toLocation = new PointF(40,500); PointF totalLocation = new PointF(40,750); PointF ticketTypeLocation = new PointF(40, 150); PointF startLocation = new PointF(40, 400); PointF destinationLocation = new PointF(40, 600); PointF priceLocation = new PointF(500, 750); //string imageFilePath = "C:\\Users\\kuehnle\\Documents\\TestWebsite\\NewTestTicket.bmp"; Bitmap tempBmp = new Bitmap(960,900); //auf das neu erstellte Bitmap draufzeichnen: using (Graphics g = Graphics.FromImage(tempBmp)) { g.Clear(Color.White); g.DrawLine(new Pen(Brushes.Black,10), StartLine1, EndLine1); g.DrawLine(new Pen(Brushes.Black,10), StartLine2, EndLine2); using (Font arialFont = new Font("Arial", 40,FontStyle.Bold)) { g.DrawString("Jakarta Commuter Train", arialFont, Brushes.Black, logoLocation); g.DrawString(ticketType, arialFont, Brushes.Black, ticketTypeLocation); } using (Font arialFont = new Font("Arial", 40, FontStyle.Underline)) { g.DrawString("From:", arialFont, Brushes.Black, fromLocation); g.DrawString("To:", arialFont, Brushes.Black, toLocation); } using (Font arialFont = new Font("Arial", 40, FontStyle.Regular)) { g.DrawString("Total:", arialFont, Brushes.Black, totalLocation); g.DrawString(start, arialFont, Brushes.Black, startLocation); g.DrawString(destination, arialFont, Brushes.Black, destinationLocation); g.DrawString(price, arialFont, Brushes.Black, priceLocation); } } //Farbtiefe auf 1 reduzieren: Bitmap ticket = tempBmp.Clone(new Rectangle(0, 0, tempBmp.Width, tempBmp.Height),PixelFormat.Format1bppIndexed); //ticket.Save(imageFilePath,System.Drawing.Imaging.ImageFormat.Bmp); //ticket.Dispose(); return ticket; }
public RotationParameters(float rotateX, float rotateY, float rotateZ, PointF rotationCenter) { m_rotateX = rotateX; m_rotateY = rotateY; m_rotateZ = rotateZ; m_rotationCenter = rotationCenter; }
public void AddLines(PointF[] points) { for (int index = 0; index < points.Length; ++index) { AddLine(points[index]); } }
public RotationParameters(float rotateX, float rotateY, float rotateZ) { m_rotateX = rotateX; m_rotateY = rotateY; m_rotateZ = rotateZ; m_rotationCenter = new PointF(0.5f, 0.5f); }
public MWLocation(float[] _points) { points = new PointF[4]; for (int i = 0; i < 4; i++) { points[i] = new PointF(); points[i].x = _points[i * 2]; points[i].y = _points[i * 2 + 1]; } p1 = new PointF(); p2 = new PointF(); p3 = new PointF(); p4 = new PointF(); p1.x = _points[0]; p1.y = _points[1]; p2.x = _points[2]; p2.y = _points[3]; p3.x = _points[4]; p3.y = _points[5]; p4.x = _points[6]; p4.y = _points[7]; }
static bool Method (PointF f) { Console.WriteLine ("Method with PointF arg: {0} {1}", f.fa, f.fb); if (f.fa != 100 || f.fb != 200) return false; return true; }
public PointF end1, end2; // the end-points of the bezier. #endregion Fields #region Constructors public Bezier(PointF end1, PointF control1, PointF control2, PointF end2) { this.end1 = end1; this.end2 = end2; this.control1 = control1; this.control2 = control2; }
public object Create (Color startColor, Color endColor, PointF startPoint, PointF endPoint) { var brush = new sd2.LinearGradientBrush (startPoint.ToSD (), endPoint.ToSD (), startColor.ToSD (), endColor.ToSD ()); return new BrushObject { Brush = brush, InitialMatrix = brush.Transform }; }
public LinearGradientBrush (PointF point1, PointF point2, Color color1, Color color2) { Status status = GDIPlus.GdipCreateLineBrush (ref point1, ref point2, color1.ToArgb (), color2.ToArgb (), WrapMode.Tile, out nativeObject); GDIPlus.CheckStatus (status); status = GDIPlus.GdipGetLineRect (nativeObject, out rectangle); GDIPlus.CheckStatus (status); }
// Find the cooeficient value for a particular point on the bezier. If the point // isn't sufficiently close to the bezier, returns NaN. The error value indicates // how close the point might be to the bezier. public float FindCoefficient(PointF point, float error) { if (! IsPointInQuad(point, error)) return float.NaN; float distance; return FindCoefficient(point, 0F, 1F, error, out distance); }
/// <summary> /// Draws the marker on a plot surface. /// </summary> /// <param name="g">graphics surface on which to draw</param> /// <param name="xAxis">The X-Axis to draw against.</param> /// <param name="yAxis">The Y-Axis to draw against.</param> public void Draw( System.Drawing.Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis ) { PointF point = new PointF( xAxis.WorldToPhysical( x_, true ).X, yAxis.WorldToPhysical( y_, true ).Y ); marker_.Draw( g, (int)point.X, (int)point.Y ); }
public object Create(Color startColor, Color endColor, PointF startPoint, PointF endPoint) { var shader = new ag.LinearGradient(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y, startColor.ToAndroid(), endColor.ToAndroid(), // is this correct? ag.Shader.TileMode.Clamp); var paint = new ag.Paint(); paint.SetShader(shader); return new BrushObject { Paint = paint }; // TODO: initial matrix }
public void NonDefaultConstructorTest(float x, float y, float width, float height) { RectangleF rect1 = new RectangleF(x, y, width, height); PointF p = new PointF(x, y); SizeF s = new SizeF(width, height); RectangleF rect2 = new RectangleF(p, s); Assert.Equal(rect1, rect2); }
public PathGradientBrush (PointF [] points, WrapMode wrapMode) { if (points == null) throw new ArgumentNullException ("points"); if ((wrapMode < WrapMode.Tile) || (wrapMode > WrapMode.Clamp)) throw new InvalidEnumArgumentException ("WrapMode"); Status status = GDIPlus.GdipCreatePathGradient (points, points.Length, wrapMode, out nativeObject); GDIPlus.CheckStatus (status); }
public Matrix (RectangleF rect, PointF[] plgpts) { if (plgpts == null) throw new ArgumentNullException ("plgpts"); if (plgpts.Length != 3) throw new ArgumentException ("plgpts"); Status status = GDIPlus.GdipCreateMatrix3 (ref rect, plgpts, out nativeMatrix); GDIPlus.CheckStatus (status); }
public static Image drawPicture(int width, int height, string msg) { Bitmap bmp = new Bitmap(width,height); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.CadetBlue); PointF p = new PointF(100,100); Font f = new Font("宋体",20,FontStyle.Regular); g.DrawString(msg,f,Brushes.Beige ,p); return (Image)bmp; }
public GraphicsPath (PointF[] pts, byte[] types, FillMode fillMode) { if (pts == null) throw new ArgumentNullException ("pts"); if (pts.Length != types.Length) throw new ArgumentException ("Invalid parameter passed. Number of points and types must be same."); Status status = GDIPlus.GdipCreatePath2 (pts, types, pts.Length, fillMode, out nativePath); GDIPlus.CheckStatus (status); }
public static Point Round(PointF value) { int x, y; checked { x = (int)Math.Round(value.X); y = (int)Math.Round(value.Y); } return new Point(x, y); }
public void CreateBarcode(Graphics g) { //g.DrawString("Code 39", new Font("Vendana", 9), Brushes.Blue, barcodeRect); // g.SetClip(barcodeRect); GraphicsState state = g.Save(); Matrix RotationTransform = new Matrix(1, 0, 0, 1, 1, 1); //rotation matrix PointF TheRotationPoint; switch (Rotation) { case BarcodeRotation.Rotation90: TheRotationPoint = new PointF(barcodeRect.X, barcodeRect.Y); RotationTransform.RotateAt(90, TheRotationPoint); g.Transform = RotationTransform; g.TranslateTransform(0, -barcodeRect.Width); break; case BarcodeRotation.Rotation270: TheRotationPoint = new PointF(barcodeRect.X, barcodeRect.Y + barcodeRect.Height); RotationTransform.RotateAt(270, TheRotationPoint); g.Transform = RotationTransform; g.TranslateTransform(0, barcodeRect.Height); break; } bool bchkValueText = false; for (int i = 0; i < code.Length; i++) { if (alphabet39.IndexOf(code[i]) == -1 || code[i] == '*') { g.DrawString("条码文本无效!", textFont, Brushes.Red, barcodeRect.X, barcodeRect.Y); bchkValueText = true; break; } } if (!bchkValueText) { int encodedStringLength = encodedString.Length; float x = barcodeRect.X; float wid = 0; int yTop = (int)barcodeRect.Y; if (bShowText) { using (StringFormat sf = new StringFormat()) { switch (align) { case BarcodeTextAlign.Left: sf.Alignment = StringAlignment.Near; break; case BarcodeTextAlign.Center: sf.Alignment = StringAlignment.Center; break; case BarcodeTextAlign.Right: sf.Alignment = StringAlignment.Far; break; } switch (Rotation) { case BarcodeRotation.Rotation90: break; case BarcodeRotation.Rotation270: break; } if (bShowTextOnTop) { //yTop += height; if (Rotation == BarcodeRotation.Rotation0) { g.DrawString(code, textFont, Brushes.Black, new RectangleF(barcodeRect.X, yTop, barcodeRect.Width, g.MeasureString("s", textFont).Height), sf); } else { g.DrawString(code, textFont, Brushes.Black, new RectangleF(barcodeRect.X, yTop, barcodeRect.Height, g.MeasureString("s", textFont).Height), sf); } yTop += Convert.ToInt32(g.MeasureString("s", textFont).Height); } else { yTop += height; if (Rotation == BarcodeRotation.Rotation0) { g.DrawString(code, textFont, Brushes.Black, new RectangleF(barcodeRect.X, yTop, barcodeRect.Width, barcodeRect.Height - height), sf); } else { g.DrawString(code, textFont, Brushes.Black, new RectangleF(barcodeRect.X, yTop, barcodeRect.Height, barcodeRect.Width), sf); } yTop -= height; } } } for (int i = 0; i < encodedStringLength; i++) { if (encodedString[i] == '1') { wid = (wideToNarrowRatio * (int)weight); } else { wid = (int)weight; } g.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, yTop, wid, height); x += wid; } } g.Restore(state); //g.ResetClip(); }
//not a fun mass of parsing. Attempts to closely match the label behaviour of the Windows 10 Start Menu. Haven't tested against Windows 8.1 //probably fails in some instances... private void DrawTextOverlay(PaintEventArgs e) { var scaleFactor = GetControlScaleFactor(); var fontScaleFactor = GetControlScaleFactorForFont(e.Graphics); if (scaleFactor == 0 || fontScaleFactor == 0) { return; } var imgBounds = ImageRectangle; var overlayBrush = new SolidBrush(TextOverlayColor); var overlayLoc = new PointF(imgBounds.X + TextOverlayLocation.X * scaleFactor, imgBounds.Y + TextOverlayLocation.Y * scaleFactor); var overlayFont = new Font(_overlayFont.FontFamily, _overlayFont.Size * fontScaleFactor, _overlayFont.Style); try { //get the width of the text before any manipulation var textWidth = e.Graphics.MeasureString(TextOverlay, overlayFont).Width; //maximum length for a string, without spaces, to fit on the initial line - TODO: Pass these values in if there is ever a new tile type available var maxSingleLineLength = 90 * scaleFactor; //maximum length of a line before truncating with ellipsis var ellipsisLength = 91 * scaleFactor; //function to loop through a line, removing a char at a time until the length satisfies the requirement Func <string, float, string> getCharsToMaxLength = (inputString, length) => { var textChunk = inputString; do { textChunk = textChunk.Substring(0, textChunk.Length - 1); } while (e.Graphics.MeasureString(textChunk, overlayFont).Width > length); return(textChunk); }; //if we have a space somewhere in the string and it's over the max single line length it will be split over two lines if (textWidth >= maxSingleLineLength && TextOverlay.Contains(" ")) { //get the first chunk of data to process var firstChunk = getCharsToMaxLength(TextOverlay, maxSingleLineLength); string firstLine; string secondLine; //different handling whether there is a space in the first chunk or not. If there *is* a space, we will grab up until the last occurrance of a space character //anything after that space character is put on the second line // //if there isn't a space in the first line, the entire chunk can be made the first line. The second line will start from where the first space character after this chunk is //EXAMPLES //1- XXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXX //This should place XXXXX XXX on line one, and XXXXXXXXXXXXXXXXXXXXXXXXXX on line two // //2- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X //This should place XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX on line one, and X on line two if (firstChunk.Contains(" ")) { var lastSpaceIndex = firstChunk.LastIndexOf(" ", StringComparison.Ordinal); firstLine = firstChunk.Substring(0, lastSpaceIndex).Trim(); secondLine = TextOverlay.Substring(lastSpaceIndex, TextOverlay.Length - lastSpaceIndex).Trim(); } else { firstLine = firstChunk; var tempSecondLine = TextOverlay.Substring(firstChunk.Length, TextOverlay.Length - firstChunk.Length).Trim(); var firstSpaceIndex = tempSecondLine.IndexOf(" ", StringComparison.Ordinal); secondLine = tempSecondLine.Substring(firstSpaceIndex, tempSecondLine.Length - firstSpaceIndex).Trim(); } //compare each line to the ellipsis length - if exceeds, truncate with ... //from previous examples above, we should now have: //1. XXXXX XXX // XXXXXXXXXX... // //2. XXXXXXXXXX... // X if (e.Graphics.MeasureString(firstLine, overlayFont).Width > ellipsisLength) { firstLine = getCharsToMaxLength(firstLine, ellipsisLength) + "..."; } if (e.Graphics.MeasureString(secondLine, overlayFont).Width > ellipsisLength) { var tempSecondLine = getCharsToMaxLength(secondLine, ellipsisLength); if (tempSecondLine.Contains(" ")) { //Another fun quirk - we only keep the parts of the second line that can be fully displayed? //Example: //XXXXXXXX XXXXXXXXXXX //becomes //XXXXXXXX... //NOT //XXXXXXXX X... var lastSpaceIndex = tempSecondLine.LastIndexOf(" ", StringComparison.Ordinal); secondLine = tempSecondLine.Substring(0, lastSpaceIndex).Trim() + "..."; } else { secondLine = tempSecondLine + "..."; } } //draw our lines, first line 16px higher than the default (?) TODO: 16 should really be passed in if new tile types ever become available e.Graphics.DrawString(firstLine, overlayFont, overlayBrush, new PointF(overlayLoc.X, overlayLoc.Y - 16 * scaleFactor)); e.Graphics.DrawString(secondLine, overlayFont, overlayBrush, overlayLoc); } else { //if we have no spaces, it'll always be on a single line. Check if the line needs truncating and display in default position var renderLine = TextOverlay; if (e.Graphics.MeasureString(renderLine, overlayFont).Width > ellipsisLength) { renderLine = getCharsToMaxLength(renderLine, ellipsisLength) + "..."; } e.Graphics.DrawString(renderLine, overlayFont, overlayBrush, overlayLoc); } } catch { //ignore a failure } finally { overlayBrush.Dispose(); overlayFont.Dispose(); } }
public void DrawLine(PointF p1, PointF p2, Color c, float weight = 1) { this.DrawLine(p1.X, p1.Y, p2.X, p2.Y, c, weight); }
public void SetPixel(PointF p, int c) { this.SetPixel((int)(p.X), (int)(p.Y), (uint)c); }
public static double GetDistance(PointF LineStartPoint, PointF LineEndPoint) { return(GetDistance(LineStartPoint.X, LineStartPoint.Y, LineEndPoint.X, LineEndPoint.Y)); }
/// <summary> /// Draws a line between the To and From connectors /// </summary> /// <param name="g">The graphics</param> protected void PaintPolyLine(Graphics g) { //style if (IsSelected) { Pen.DashStyle = DashStyle.Dash; } else { if (mLineStyle != DashStyle.Custom) { Pen.DashStyle = mLineStyle; } else { Pen.DashStyle = DashStyle.Solid; } } if (From == null) { return; } PointF s = From.BelongsTo.ConnectionPoint(From); PointF e = (To != null) ? To.BelongsTo.ConnectionPoint(To) : mToPoint; //this is for the Omni connector, a central connector double len = Math.Sqrt((e.X - s.X) * (e.X - s.X) + (e.Y - s.Y) * (e.Y - s.Y)); if (len > 0 && To != null && this.To.ConnectorLocation == ConnectorLocation.Omni) { e.X -= Convert.ToSingle((e.X - s.X) * To.ConnectionShift / len); e.Y -= Convert.ToSingle((e.Y - s.Y) * To.ConnectionShift / len); } if (len > 0 && From != null && this.From.ConnectorLocation == ConnectorLocation.Omni) { s.X -= Convert.ToSingle((e.X - s.X) * 10 / len); s.Y -= Convert.ToSingle((e.Y - s.Y) * 10 / len); } //now, for the normal connectors if ((s.X != e.X) || (s.Y != e.Y)) { mPainter.IsHovered = IsHovered; switch (this.mLinePath) { case "Default": { mPainter.Points = this.GetConnectionPoints(); //update points to reflect the user actions/motions break; } case "Bezier": { if (mFrom.ConnectorLocation == ConnectorLocation.Unknown) { (mPainter as BezierPainter).Handles[0].ChangeLocation(s); } else { (mPainter as BezierPainter).Handles[0].ChangeLocation(mFrom.AdjacentPoint); } if (mTo == null || mTo.ConnectorLocation == ConnectorLocation.Unknown) { (mPainter as BezierPainter).Handles[(mPainter as BezierPainter).Handles.Count - 1].ChangeLocation(e); } else { (mPainter as BezierPainter).Handles[(mPainter as BezierPainter).Handles.Count - 1].ChangeLocation(mTo.AdjacentPoint); } break; } case "Rectangular": { mPainter.Points = GetConnectionPoints(); //update points to reflect the user actions/motions break; } default: mPainter.Points = GetConnectionPoints(); break; } mPainter.Paint(g); if (IsHovered || IsSelected) { this.mTracker.Paint(g); } } PointF left = PointF.Empty, right = PointF.Empty; #region the end arrow if (LineEnd == ConnectionEnd.BothFilledArrow || LineEnd == ConnectionEnd.BothOpenArrow || LineEnd == ConnectionEnd.RightFilledArrow || LineEnd == ConnectionEnd.RightOpenArrow) { switch (this.mTo.ConnectorLocation) { case ConnectorLocation.North: left = new PointF(e.X + 4, e.Y - 7); right = new PointF(e.X - 4, e.Y - 7); break; case ConnectorLocation.South: left = new PointF(e.X - 4, e.Y + 7); right = new PointF(e.X + 4, e.Y + 7); break; case ConnectorLocation.West: left = new PointF(e.X - 7, e.Y - 4); right = new PointF(e.X - 7, e.Y + 4); break; case ConnectorLocation.East: left = new PointF(e.X + 7, e.Y + 4); right = new PointF(e.X + 7, e.Y - 4); break; case ConnectorLocation.Unknown: return; } if (LineEnd == ConnectionEnd.RightFilledArrow || LineEnd == ConnectionEnd.BothFilledArrow) { PaintArrow(g, e, left, right, true); } else { PaintArrow(g, e, left, right, false); } //the omni arrow is a bit more difficult if (this.mTo.ConnectorLocation == ConnectorLocation.Omni) { if (LineEnd == ConnectionEnd.RightFilledArrow || LineEnd == ConnectionEnd.BothFilledArrow) { PaintArrow(g, s, e, mLineColor, true, false); } else { PaintArrow(g, s, e, mLineColor, false, false); } } } #endregion #region the start or From arrow if (LineEnd == ConnectionEnd.BothFilledArrow || LineEnd == ConnectionEnd.BothOpenArrow || LineEnd == ConnectionEnd.LeftFilledArrow || LineEnd == ConnectionEnd.LeftOpenArrow) { switch (this.mFrom.ConnectorLocation) { case ConnectorLocation.North: left = new PointF(s.X + 4, s.Y - 7); right = new PointF(s.X - 4, s.Y - 7); break; case ConnectorLocation.South: left = new PointF(s.X - 4, s.Y + 7); right = new PointF(s.X + 4, s.Y + 7); break; case ConnectorLocation.West: left = new PointF(s.X - 7, s.Y - 4); right = new PointF(s.X - 7, s.Y + 4); break; case ConnectorLocation.East: left = new PointF(s.X + 7, s.Y + 4); right = new PointF(s.X + 7, s.Y - 4); break; case ConnectorLocation.Unknown: return; } if (LineEnd == ConnectionEnd.LeftFilledArrow || LineEnd == ConnectionEnd.BothFilledArrow) { PaintArrow(g, s, left, right, true); } else { PaintArrow(g, s, left, right, false); } //the omni arrow is a bit more difficult if (this.mTo.ConnectorLocation == ConnectorLocation.Omni) { if (LineEnd == ConnectionEnd.LeftFilledArrow || LineEnd == ConnectionEnd.BothFilledArrow) { PaintArrow(g, e, s, mLineColor, true, false); } else { PaintArrow(g, e, s, mLineColor, false, false); } } } #endregion }
private static IEnumerable <RectangleF> ComputeBoundingRectangles(GraphicsPath path, PointF offset) { var bounds = path.GetBounds(); var h = Math.Max((int)bounds.Height, BlockSize); var w = Math.Max((int)bounds.Width, BlockSize); using (var image = new Bitmap(w, h)) { using (var gfx = Graphics.FromImage(image)) { var m = new Matrix(); m.Translate(-bounds.X + 1, -bounds.Y + 1); path.Transform(m); gfx.FillPath(new SolidBrush(Color.White), path); } var imageWidth = image.Width; var imageHeight = image.Height; var bitmapData = image.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), ImageLockMode.ReadOnly, image.PixelFormat); var ptr = bitmapData.Scan0; var numBytes = bitmapData.Stride * imageHeight; var bytes = new byte[numBytes]; Marshal.Copy(ptr, bytes, 0, numBytes); for (var bx = 0; bx < w; bx += BlockSize) { for (var by = 0; by < h; by += BlockSize) { if (CheckBlock(bx, by, bytes, imageWidth, imageHeight)) { yield return(new RectangleF(bx + offset.X, by + offset.Y, BlockSize, BlockSize)); } } } } }
// Draw the polygons and their union. private void picCanvas_Paint(object sender, PaintEventArgs e) { e.Graphics.Clear(picCanvas.BackColor); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // If we have both polygons, draw the union. if ((MakingIndex < 0) && (polygons[0].Count > 2) && (polygons[1].Count > 2) && (chkUnion.Checked)) { // Find the union. List <PointF> union = _IOperation.FindPolygonUnion(polygons); // Draw it. using (Pen pen = new Pen(Color.Black, 10)) { e.Graphics.DrawPolygon(pen, union.ToArray()); } } // Draw the polygons. for (int i = 0; i < 2; i++) { if (PolygonCheckboxes[i].Checked) { // See if we are making this polygon. if (i == MakingIndex) { // We are. Draw the segments so far. if (polygons[i].Count > 1) { using (Pen pen = new Pen(PolygonColors[i], 3)) { e.Graphics.DrawLines(pen, polygons[i].ToArray()); } } // Draw to the mouse's current location. if (polygons[i].Count > 0) { PointF point1 = polygons[i][polygons[i].Count - 1]; e.Graphics.DrawLine(Pens.Green, point1.X, point1.Y, CurrentLocation.X, CurrentLocation.Y); } } else { // We're not making this polygon. Draw it. if (polygons[i].Count > 2) { Color fill_color = Color.FromArgb(128, PolygonColors[i]); using (Brush brush = new SolidBrush(fill_color)) { e.Graphics.FillPolygon(brush, polygons[i].ToArray()); } using (Pen pen = new Pen(PolygonColors[i], 3)) { e.Graphics.DrawPolygon(pen, polygons[i].ToArray()); } } } } } }
/// <summary> /// 计算两条直线的交点 /// </summary> /// <param name="lineFirstStar">L1的点1坐标</param> /// <param name="lineFirstEnd">L1的点2坐标</param> /// <param name="lineSecondStar">L2的点1坐标</param> /// <param name="lineSecondEnd">L2的点2坐标</param> /// <returns></returns> private bool GetIntersection(PointF lineFirstStar, PointF lineFirstEnd, PointF lineSecondStar, PointF lineSecondEnd, out PointF linInt) { //* L1,L2都存在斜率的情况: //* 直线方程L1: ( y - y1 ) / ( y2 - y1 ) = ( x - x1 ) / ( x2 - x1 ) //* => y = [ ( y2 - y1 ) / ( x2 - x1 ) ]( x - x1 ) + y1 //* 令 a = ( y2 - y1 ) / ( x2 - x1 ) //* 有 y = a * x - a * x1 + y1 .........1 //* 直线方程L2: ( y - y3 ) / ( y4 - y3 ) = ( x - x3 ) / ( x4 - x3 ) //* 令 b = ( y4 - y3 ) / ( x4 - x3 ) //* 有 y = b * x - b * x3 + y3 ..........2 //* 如果 a = b,则两直线平等,否则, 联解方程 1,2,得: //* x = ( a * x1 - b * x3 - y1 + y3 ) / ( a - b ) //* y = a * x - a * x1 + y1 //* L1存在斜率, L2平行Y轴的情况: //* x = x3 //* y = a * x3 - a * x1 + y1 //* L1 平行Y轴,L2存在斜率的情况: //* x = x1 //* y = b * x - b * x3 + y3 //* L1与L2都平行Y轴的情况: //* 如果 x1 = x3,那么L1与L2重合,否则平等 bool bRet = false; linInt = new PointF(0, 0); float a = 0, b = 0, x, y; int state = 0; if (lineFirstStar.X != lineFirstEnd.X) { a = (lineFirstEnd.Y - lineFirstStar.Y) / (lineFirstEnd.X - lineFirstStar.X); state |= 1; } if (lineSecondStar.X != lineSecondEnd.X) { b = (lineSecondEnd.Y - lineSecondStar.Y) / (lineSecondEnd.X - lineSecondStar.X); state |= 2; } switch (state) { case 0: //L1与L2都平行Y轴 if (lineFirstStar.X == lineSecondStar.X) { //throw new Exception("两条直线互相重合,且平行于Y轴,无法计算交点。"); //return new PointF(0, 0); } else { //throw new Exception("两条直线互相平行,且平行于Y轴,无法计算交点。"); //return new PointF(0, 0); } break; case 1: //L1存在斜率, L2平行Y轴 x = lineSecondStar.X; y = (lineFirstStar.X - x) * (-a) + lineFirstStar.Y; linInt = new PointF(x, y); bRet = true; break; case 2: //L1 平行Y轴,L2存在斜率 x = lineFirstStar.X; //网上有相似代码的,这一处是错误的。你可以对比case 1 的逻辑 进行分析 //源code:lineSecondStar * x + lineSecondStar * lineSecondStar.X + p3.Y; y = (lineSecondStar.X - x) * (-b) + lineSecondStar.Y; linInt = new PointF(x, y); bRet = true; break; case 3: //L1,L2都存在斜率 if (a == b) { // throw new Exception("两条直线平行或重合,无法计算交点。"); //return new PointF(0, 0); } x = (a * lineFirstStar.X - b * lineSecondStar.X - lineFirstStar.Y + lineSecondStar.Y) / (a - b); y = a * x - a * lineFirstStar.X + lineFirstStar.Y; linInt = new PointF(x, y); bRet = true; break; } return(bRet); }
private void button1_Click(object sender, EventArgs e) { Bitmap bm = new Bitmap(500, 500); Graphics gh = Graphics.FromImage(bm); gh.Clear(Color.White); PointF cPt = new PointF(40, 420); //中心点 PointF[] xPt = new PointF[3] { new PointF(cPt.Y + 15, cPt.Y), new PointF(cPt.Y, cPt.Y - 8), new PointF(cPt.Y, cPt.Y + 8) }; //X轴三角形 PointF[] yPt = new PointF[3] { new PointF(cPt.X, cPt.X - 15), new PointF(cPt.X + 8, cPt.X), new PointF(cPt.X - 8, cPt.X) }; //Y轴三角形 gh.DrawString("某工厂某产品月生产量图表", new Font("宋体", 14), Brushes.Black, new PointF(cPt.X + 12, cPt.X)); //画X轴 gh.DrawLine(Pens.Black, cPt.X, cPt.Y, cPt.Y, cPt.Y); gh.DrawPolygon(Pens.Black, yPt); gh.FillPolygon(new SolidBrush(Color.Black), xPt); gh.DrawString("月份", new Font("宋体", 12), Brushes.Black, new PointF(cPt.Y + 12, cPt.Y - 10)); //画Y轴 gh.DrawLine(Pens.Black, cPt.X, cPt.Y, cPt.X, cPt.X); gh.DrawPolygon(Pens.Black, yPt); gh.FillPolygon(new SolidBrush(Color.Black), yPt); gh.DrawString("单位(万)", new Font("宋体", 12), Brushes.Black, new PointF(6, 7)); for (int i = 1; i <= 12; i++) { //画Y轴刻度 if (i < 11) { gh.DrawString((i * 10).ToString(), new Font("宋体", 11), Brushes.Black, new PointF(cPt.X - 30, cPt.Y - i * 30 - 6)); gh.DrawLine(Pens.Black, cPt.X - 3, cPt.Y - i * 30, cPt.X, cPt.Y - i * 30); } //画X轴项目 gh.DrawString(month[i - 1].Substring(0, 1), new Font("宋体", 11), Brushes.Black, new PointF(cPt.X + i * 30 - 5, cPt.Y + 5)); gh.DrawString(month[i - 1].Substring(1, 1), new Font("宋体", 11), Brushes.Black, new PointF(cPt.X + i * 30 - 5, cPt.Y + 20)); if (month[i - 1].Length > 2) { gh.DrawString(month[i - 1].Substring(2, 1), new Font("宋体", 11), Brushes.Black, new PointF(cPt.X + i * 30 - 5, cPt.Y + 35)); } //画点 gh.DrawEllipse(Pens.Black, cPt.X + i * 30 - 1.5F, cPt.Y - d[i - 1] * 3 + 1.5F, 3, 3); gh.FillEllipse(new SolidBrush(Color.Black), cPt.X + i * 30 - 1.5F, cPt.Y - d[i - 1] * 3 + 1.5F, 3, 3); //画数值 gh.DrawString(d[i - 1].ToString(), new Font("宋体", 11), Brushes.Black, new PointF(cPt.X + i * 30, cPt.Y - d[i - 1] * 3)); //画折线 if (i > 1) { gh.DrawLine(Pens.Red, cPt.X + (i - 1) * 30, cPt.Y - d[i - 2] * 3, cPt.X + i * 30, cPt.Y - d[i - 1] * 3); } } //显示在pictureBox控件中 this.pictureBox1.Image = bm; }
private void UpdateBitmap() { if (colors == null) { colors = new Color[720]; for (int i = 0; i < colors.Length; i++) { colors[i] = ColorFromHsv(i / 2d, 1, 1); } } if (bitmap == null || bitmap.Width != Area.Width || bitmap.Height != Area.Height) { bitmap = new NBitmap(Area.Width, Area.Height); distances = new int[Area.Height, Area.Width]; PointF center = new PointF(Area.Width / 2f, Area.Height / 2f); double radius = Math.Min(Area.Height, Area.Width) * 3d / 8; PointF[] points = new PointF[9]; for (int i = 0; i < points.Length; i++) { double angle = i * 2 * Math.PI / points.Length - Math.PI / 2; points[i] = new PointF(center.X + (float)(Math.Cos(angle) * radius), center.Y + (float)(Math.Sin(angle) * radius)); } Parallel.For(0, bitmap.Height, y => { for (int x = 0; x < bitmap.Width; x++) { double distSum = 0; double weightSum = 0; for (int i = 0; i < points.Length; i++) { double dist = GetDistance(new PointF(x, y), points[i]); double weight = Math.Pow(1 / (1 + dist), 2); distSum += dist * weight; weightSum += weight; } double wDist = distSum / weightSum; distances[y, x] = (int)(wDist * 4); } }); } int time = (int)DateTime.Now.TimeOfDay.TotalMilliseconds; Parallel.For(0, bitmap.Height, y => { for (int x = 0; x < bitmap.Width; x++) { int dist = distances[y, x]; int colorIndex = (dist - time / 4) % colors.Length; if (colorIndex < 0) { colorIndex += colors.Length; } bitmap.SetColor(x, y, colors[colorIndex]); } }); }
/// <summary> /// Draws the specified graphics. /// </summary> /// <param name="graphics">The graphics.</param> /// <param name="font">The font.</param> /// <param name="brush">The brush.</param> /// <param name="pen">The pen.</param> /// <param name="location">The location.</param> /// <param name="scale">The scale.</param> /// <param name="drawBorders">if set to <see langword="true" /> [draw borders].</param> /// <exception cref="NotImplementedException"></exception> /// <exception cref="NotImplementedException"></exception> public void Draw(Graphics graphics, Font font, Brush brush, Pen pen, PointF location, float scale, bool drawBorders = false) => throw new NotImplementedException();
public static PointF[] GetInterpolatedPointArray(Point[] Points, int Segments) { // Create an empty return collection to store interpolated points List <PointF> interpolatedPoints = new List <PointF>(Segments); // Precalculate desired segment length and define helper variables double desiredSegmentLength = GetPointArrayLength(Points) / Segments; double dCurrSegmentLength, dTestSegmentLength, dIncToCurrentlength, dInterpolationPosition; PointF currentPoint; dCurrSegmentLength = 0; // Initialize to zero // Add first point in point pattern to return array and save it for use in the interpolation process PointF lastTestPoint = Points[0]; // Initialize to first point in point pattern interpolatedPoints.Add(lastTestPoint); // Enumerate points starting with second point (if any) for (int currentIndex = 1; currentIndex < Points.Length; currentIndex++) { // Store current index point in helper variable currentPoint = Points[currentIndex]; // Calculate distance between last added point and current point in point pattern // and use calculated length to calculate test segment length for next point to add dIncToCurrentlength = GetDistance(lastTestPoint, currentPoint); dTestSegmentLength = dCurrSegmentLength + dIncToCurrentlength; // Does the test segment length meet our desired length requirement if (dTestSegmentLength < desiredSegmentLength) { // Desired segment length has not been satisfied so we don't need to add an interpolated point // save this test point and move on to next test point dCurrSegmentLength = dTestSegmentLength; lastTestPoint = currentPoint; continue; } // Test segment length has met or exceeded our desired segment length // so lets calculate how far we overshot our desired segment length and calculate // an interpolation position to use to derive our new interpolation point dInterpolationPosition = (desiredSegmentLength - dCurrSegmentLength) * (1 / dIncToCurrentlength); // Use interpolation position to derive our new interpolation point PointF interpolatedPoint = GetInterpolatedPoint(lastTestPoint, currentPoint, dInterpolationPosition); interpolatedPoints.Add(interpolatedPoint); // Sometimes rounding errors cause us to attempt to add more points than the user has requested. // If we've reached our segment count limit, exit loop if (interpolatedPoints.Count == Segments) { break; } // Store new interpolated point as last test point for use in next segment calculations // reset current segment length and jump back to the last index because we aren't done with original line segment lastTestPoint = interpolatedPoint; dCurrSegmentLength = 0; currentIndex--; } // Return interpolated point array return(interpolatedPoints.ToArray()); }
public CircleF(PointF center, float radius);
private void PictureBox_MouseDown(object sender, MouseEventArgs e) { if ((Mode == MouseMode.Pan && e.Button == MouseButtons.Left) || (e.Button == MouseButtons.Middle)) { // Start panning the image PanStartMousePosition = e.Location; PanStartPicturePosition = PictureBox.PicturePosition; } else if ((Mode == MouseMode.Pick || Mode == MouseMode.Erase) && e.Button == MouseButtons.Left && ActiveAnnotation == null) { // Pick and activate annotation and possibly also control point var result = PictureBox.FindAnnotation(e.Location); if (result != null) { if (Mode == MouseMode.Pick) { ActiveAnnotation = result.Item1; ActiveControlPoint = result.Item2; oldControlPointLocations.Clear(); oldControlPointLocations.AddRange(ActiveAnnotation.ControlPoints); controlPointSelectLocation = new Vec3(PictureBox.ScreenToPicture(new Vec2(e.Location)), PictureBox.Slice); } else { // Erase annotation PictureBox.Annotations.Remove(result.Item1); Refresh(); } } } else if ((Mode == MouseMode.AddAnnotation || Mode == MouseMode.Profile) && e.Button == MouseButtons.Left && ActiveAnnotation == null) { if (Mode == MouseMode.Profile) { NewAnnotationName = "Line segment"; EraseProfileAnnotation(); } // Add new annotation object if (!String.IsNullOrEmpty(NewAnnotationName)) { ActiveAnnotation = AnnotationFactory.Create(NewAnnotationName); PictureBox.Annotations.Add(ActiveAnnotation); Vec3 pos = new Vec3(PictureBox.ScreenToPicture(new Vec2(e.Location)), PictureBox.Slice); ActiveAnnotation.ControlPoints.Add(pos); ActiveControlPoint = 0; // Add another control point right away if multiple points are required. if (ActiveAnnotation.RequiredPointCount > 1) { ActiveAnnotation.ControlPoints.Add(pos); ActiveControlPoint = 1; } Refresh(); if (Mode != MouseMode.Profile) { if (ToolStrip != null) { ToolStrip.ResetAnnotation(); } } } if (Mode == MouseMode.Profile) { ProfileAnnotation = ActiveAnnotation; UpdateProfile(); } } }
public void DrawLine(Pen pen, PointF pt1, PointF pt2) { graphics.DrawLine(pen, pt1, pt2); }
public uint GetPixel(PointF v) { return(this.GetPixel((int)v.X, (int)v.Y)); }
public void DrawString(string s, Font font, Brush brush, PointF point, StringFormat format) { graphics.DrawString(s, font, brush, point, format); }
public override void Ctrl() { base.Ctrl(); if (!this.OnSpell) { this.Armon = 0.0f; } switch (this.Life) { case 0: this.Velocity = 0.0f; this.DestPoint = (PointF) new Point(this.Ran.Next(100, this.BoundRect.Width - 100), this.Ran.Next(70, 200)); break; case 1: this.Ctrl1(); break; } this.MoveToPoint(this.DestPoint); if (!this.OnSpell) { if ((double)this.HealthPoint >= (double)this.SpellcardHP && this.Time <= this.SpellTime) { return; } this.HealthPoint = (float)this.SpellcardHP; this.Time = 0; this.OnSpell = true; ShootingStarShard shootingStarShard = new ShootingStarShard(this.StageData, new PointF((float)(this.BoundRect.Width / 2), 0.0f)); } else if ((double)this.HealthPoint <= 0.0 || this.Time > this.SpellTime) { --this.Life; this.OnAction = 0; Rectangle boundRect; if ((double)this.HealthPoint <= 0.0 && this.Life >= -1) { this.GiveItems(); StageDataPackage stageData = this.StageData; boundRect = this.BoundRect; PointF OriginalPosition = new PointF((float)(boundRect.Width / 2), 0.0f); ShootingStarShard shootingStarShard = new ShootingStarShard(stageData, OriginalPosition); } if (this.Life <= 0) { if (this.Life == 0) { this.DestPoint = (PointF) new Point(this.Ran.Next((int)this.OriginalPosition.X - 30, (int)this.OriginalPosition.X + 30), this.Ran.Next((int)this.OriginalPosition.Y + 30, (int)this.OriginalPosition.Y + 50)); this.Velocity = 0.5f; BulletRemover2 bulletRemover2 = new BulletRemover2(this.StageData, this.OriginalPosition); this.HealthPoint = 0.0f; this.GiveEndEffect(); this.Life = -1; } } else { BulletRemover2 bulletRemover2 = new BulletRemover2(this.StageData, this.OriginalPosition); this.StageData.SoundPlay("se_tan00.wav"); this.HealthPoint = (float)this.MaxHP; this.Time = 0; this.OnSpell = false; boundRect = this.BoundRect; this.DestPoint = (PointF) new Point(boundRect.Width / 2, 120); this.Velocity = 4f; } } }
Bitmap draw_font(String Text, int kt) { Bitmap bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height); if (kt == 0) { if (textBox1.Text == "") { MessageBox.Show("Vui lòng chọn bộ mã hoặc tự gõ bộ mã của riêng bạn"); return(bitmap); } if (textBox3.Text == "") { MessageBox.Show("Vui lòng chọn font kiểu UTF8 có sẵn trong máy tính của bạn"); return(bitmap); } if (textBox1.Text == "") { MessageBox.Show("Vui lòng chọn font kiểu UTF8 có sẵn trong máy tính của bạn"); return(bitmap); } } pictureBox1.Size = new Size(pictureBox1.Width, pictureBox1.Height); try { PointF Location = new PointF(0, 0); //fill while Graphics gfx = Graphics.FromImage(bitmap); SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255)); gfx.FillRectangle(brush, 0, 0, bitmap.Width, bitmap.Height); Graphics graphics = Graphics.FromImage(bitmap); Font Font = new Font(fontName, fontSize); graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; graphics.DrawString(Text, Font, Brushes.Black, Location); } catch { return(bitmap); } int minx = bitmap.Width, miny = bitmap.Height, maxx = 0, maxy = 0; for (int x = 0; x < bitmap.Width; x++) //tìm điểu cuối xy { for (int y = 0; y < bitmap.Height; y++) { Color c = bitmap.GetPixel(x, y); if (c.R == 0 && c.G == 0 && c.B == 0) { if (x < minx) { minx = x; } if (y < miny) { miny = y; } } } } for (int x = 0; x < bitmap.Width; x++) //tìm điểu cuối xy { for (int y = 0; y < bitmap.Height; y++) { Color c = bitmap.GetPixel(x, y); if (c.R == 0 && c.G == 0 && c.B == 0) { if (x > maxx) { maxx = x; } if (y > maxy) { maxy = y; } } } } if (maxx == 0 && maxy == 0) { minx = 0; miny = 0; maxx = Int16.Parse(numericUpDown1.Text) - 1; maxy = 0; } if (maxy > mid_line) { offset = maxy - mid_line - 1; } else { offset = 0; } if (kt == 0) { pictureBox1.Image = CropImage(bitmap, minx, miny, maxx, maxy); } return(CropImage(bitmap, minx, miny, maxx, maxy)); }
public bool IsVisible(PointF point) { return(graphics.IsVisible(point)); }
protected override void OnPaint(PaintEventArgs e) { using (SolidBrush b = new SolidBrush(BackColor)) { e.Graphics.FillRectangle(b, ClientRectangle); } RectangleF lr = ClientRectangleF; Pen framepen = new Pen(m_frameColor, 1); Util.DrawFrame(e.Graphics, lr, 6, m_frameColor); if (Text.Length > 0) { StringFormat format = new StringFormat(); string alignment = TextAlign.ToString(); if (((int)TextAlign & (int)(ContentAlignment.BottomLeft | ContentAlignment.MiddleLeft | ContentAlignment.TopLeft)) != 0) { format.Alignment = StringAlignment.Near; } if (((int)TextAlign & (int)(ContentAlignment.BottomCenter | ContentAlignment.MiddleCenter | ContentAlignment.TopCenter)) != 0) { format.Alignment = StringAlignment.Center; } if (((int)TextAlign & (int)(ContentAlignment.BottomRight | ContentAlignment.MiddleRight | ContentAlignment.TopRight)) != 0) { format.Alignment = StringAlignment.Far; } if (((int)TextAlign & (int)(ContentAlignment.BottomLeft | ContentAlignment.BottomCenter | ContentAlignment.BottomRight)) != 0) { format.LineAlignment = StringAlignment.Far; } if (((int)TextAlign & (int)(ContentAlignment.MiddleLeft | ContentAlignment.MiddleCenter | ContentAlignment.MiddleRight)) != 0) { format.LineAlignment = StringAlignment.Center; } if (((int)TextAlign & (int)(ContentAlignment.TopLeft | ContentAlignment.TopCenter | ContentAlignment.TopRight)) != 0) { format.LineAlignment = StringAlignment.Near; } Rectangle r = ClientRectangle; r.X += Padding.Left; r.Y += Padding.Top; r.Width -= Padding.Right; r.Height -= Padding.Bottom; using (SolidBrush b = new SolidBrush(ForeColor)) { if (TextAngle == 0) { e.Graphics.DrawString(Text, Font, b, r, format); } else { PointF center = Util.Center(ClientRectangle); switch (RotatePointAlignment) { case ContentAlignment.TopLeft: center.X = r.Left; center.Y = r.Top; break; case ContentAlignment.TopCenter: center.Y = r.Top; break; case ContentAlignment.TopRight: center.X = r.Right; center.Y = r.Top; break; case ContentAlignment.MiddleLeft: center.X = r.Left; break; case ContentAlignment.MiddleCenter: break; case ContentAlignment.MiddleRight: center.X = r.Right; break; case ContentAlignment.BottomLeft: center.X = r.Left; center.Y = r.Bottom; break; case ContentAlignment.BottomCenter: center.Y = r.Bottom; break; case ContentAlignment.BottomRight: center.X = r.Right; center.Y = r.Bottom; break; } center.X += Padding.Left; center.Y += Padding.Top; center.X -= Padding.Right; center.Y -= Padding.Bottom; e.Graphics.TranslateTransform(center.X, center.Y); e.Graphics.RotateTransform(TextAngle); e.Graphics.DrawString(Text, Font, b, new PointF(0, 0), format); e.Graphics.ResetTransform(); } } } RaisePaintEvent(this, e); }
public DuhringLine(IProcessVarOwner owner, double concentratn, PointF startPoint, PointF endPoint) { concentration = new ProcessVarDouble(StringConstants.MASS_CONCENTRATION, PhysicalQuantity.Unknown, concentratn, VarState.Specified, owner); startSolventBoilingPoint = new ProcessVarDouble(StringConstants.SOLVENT_BOILING_POINT, PhysicalQuantity.Temperature, startPoint.X, VarState.Specified, owner); startSolutionBoilingPoint = new ProcessVarDouble(StringConstants.SOLUTION_BOILING_POINT, PhysicalQuantity.Temperature, startPoint.Y, VarState.Specified, owner); endSolventBoilingPoint = new ProcessVarDouble(StringConstants.SOLVENT_BOILING_POINT, PhysicalQuantity.Temperature, endPoint.X, VarState.Specified, owner); endSolutionBoilingPoint = new ProcessVarDouble(StringConstants.SOLUTION_BOILING_POINT, PhysicalQuantity.Temperature, endPoint.Y, VarState.Specified, owner); }
public SizeF MeasureString(string text, Font font, PointF origin, StringFormat stringFormat) { return(graphics.MeasureString(text, font, origin, stringFormat)); }
private static List<PointF> ECG_TP (Patient p, Lead l, float _L, float _mV, PointF _S) { return Plotting.Line (ResolutionTime, _L, _mV + baseLeadCoeff [(int)l.Value, (int)WavePart.TP], _S); }
public void DrawBezier(Pen pen, PointF pt1, PointF pt2, PointF pt3, PointF pt4) { graphics.DrawBezier(pen, pt1, pt2, pt3, pt4); }
public override void Render(Settings settings) { brush = new SolidBrush(color); PointF[] PointBefore; PointF[] PointAfter; int searchFrom; int searchTo; // Calculate point before displayed points int pointBeforeIndex = Array.BinarySearch(xs, minRenderIndex, maxRenderIndex - minRenderIndex + 1, Convert.ChangeType(settings.axes.x.Min, typeof(TX))); if (pointBeforeIndex < 0) { pointBeforeIndex = ~pointBeforeIndex; } if (pointBeforeIndex > minRenderIndex) { PointBefore = new PointF[] { settings.GetPixel(Convert.ToDouble(xs[pointBeforeIndex - 1]), minmaxSearchStrategy.SourceElement(pointBeforeIndex - 1)) }; searchFrom = pointBeforeIndex; } else { PointBefore = new PointF[] { }; searchFrom = minRenderIndex; } // Calculate point after displayed points int pointAfterIndex = Array.BinarySearch(xs, minRenderIndex, maxRenderIndex - minRenderIndex + 1, Convert.ChangeType(settings.axes.x.Max, typeof(TX))); if (pointAfterIndex < 0) { pointAfterIndex = ~pointAfterIndex; } if (pointAfterIndex <= maxRenderIndex) { PointAfter = new PointF[] { settings.GetPixel(Convert.ToDouble(xs[pointAfterIndex]), minmaxSearchStrategy.SourceElement(pointAfterIndex)) }; searchTo = pointAfterIndex; } else { PointAfter = new PointF[] { }; searchTo = maxRenderIndex; } IEnumerable <PointF> VisiblePoints; if (useParallel) { VisiblePoints = Enumerable.Range(0, settings.dataSize.Width) .AsParallel() .AsOrdered() .Select(x => ProcessInterval(x, searchFrom, searchTo - searchFrom + 1, settings)) .SelectMany(x => x); } else { VisiblePoints = Enumerable.Range(0, settings.dataSize.Width) .Select(x => ProcessInterval(x, searchFrom, searchTo - searchFrom + 1, settings)) .SelectMany(x => x); } PointF[] PointsToDraw = PointBefore.Concat(VisiblePoints).Concat(PointAfter).ToArray(); // Interpolate before displayed point to make it x = -1 (close to visible area) // this fix extreme zoom in bug if (PointBefore.Length > 0 && PointsToDraw.Length >= 2) { float x0 = -1; float y0 = PointsToDraw[1].Y + (PointsToDraw[0].Y - PointsToDraw[1].Y) * (x0 - PointsToDraw[1].X) / (PointsToDraw[0].X - PointsToDraw[1].X); PointsToDraw[0] = new PointF(x0, y0); } // Interpolate after displayed point to make it x = datasize.Width(close to visible area) // this fix extreme zoom in bug if (PointAfter.Length > 0 && PointsToDraw.Length >= 2) { PointF lastPoint = PointsToDraw[PointsToDraw.Length - 2]; PointF afterPoint = PointsToDraw[PointsToDraw.Length - 1]; float x1 = settings.dataSize.Width; float y1 = lastPoint.Y + (afterPoint.Y - lastPoint.Y) * (x1 - lastPoint.X) / (afterPoint.X - lastPoint.X); PointsToDraw[PointsToDraw.Length - 1] = new PointF(x1, y1); } // Draw lines if (PointsToDraw.Length > 1) { settings.gfxData.DrawLines(penHD, PointsToDraw.ToArray()); } // draw markers if (PointsToDraw.Length > 1) { float dataSpanXPx = PointsToDraw[PointsToDraw.Length - 1].X - PointsToDraw[0].X; float markerPxRadius = .3f * dataSpanXPx / PointsToDraw.Length; markerPxRadius = Math.Min(markerPxRadius, markerSize / 2); if (markerPxRadius > .3) { // skip not visible before and after points var PointsWithMarkers = PointsToDraw .Skip(PointBefore.Length) .Take(PointsToDraw.Length - PointBefore.Length - PointAfter.Length); foreach (PointF pt in PointsWithMarkers) { // adjust marker offset to improve rendering on Linux and MacOS float markerOffsetX = (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) ? 0 : 1; settings.gfxData.FillEllipse(brush, x: pt.X - markerPxRadius + markerOffsetX, y: pt.Y - markerPxRadius, width: markerPxRadius * 2, height: markerPxRadius * 2); } } } }
public static double GetAngularGradient(PointF LineStartPoint, PointF LineEndPoint) { return(Math.Atan2((LineEndPoint.Y - LineStartPoint.Y), (LineEndPoint.X - LineStartPoint.X))); }
/// <summary> /// /// </summary> /// <param name="lin"></param> /// <param name="ptInt1"></param> /// <param name="ptInt2"></param> /// <returns></returns> public int intersectWith(GE_Line lin, out GE_Point ptInt1, out GE_Point ptInt2) { int nRet = 0; ptInt1 = new GE_Point(0, 0); ptInt2 = new GE_Point(0, 0); double A, B, a, b, c, d, P, Q, AA, BB, CC, X1, X2, Y1, Y2; double u; if (m_Kind == 0 && lin.m_Kind == 0) { PointF point1 = new PointF((float)m_StartPoint.X, (float)m_StartPoint.Y); PointF point2 = new PointF((float)m_EndPoint.X, (float)m_EndPoint.Y); PointF point3 = new PointF((float)lin.m_StartPoint.X, (float)lin.m_StartPoint.Y); PointF point4 = new PointF((float)lin.m_EndPoint.X, (float)lin.m_EndPoint.Y); PointF pointResult; if (GetIntersection(point1, point2, point3, point4, out pointResult)) { ptInt1.X = pointResult.X; ptInt1.Y = pointResult.Y; nRet = 1; } //double x11, y11, x12, y12, x21, y21, x22, y22; //x11 = m_StartPoint.X; //y11 = m_StartPoint.Y; //x12 = m_EndPoint.X; //y12 = m_EndPoint.Y; //x21 = lin.m_StartPoint.X; //y21 = lin.m_StartPoint.Y; //x22 = lin.m_EndPoint.X; //y22 = lin.m_EndPoint.Y; //u = (x11 - x21) / ((x22 - x21) - (x12 - x11)); //ptInt1.X = x11 + u * (x12 - x11); //ptInt1.Y = y11 + u * (y12 - y11); //nRet = 1; } else if (m_Kind == 1 && lin.m_Kind == 1) { A = m_CenterPoint.distanceTo(m_StartPoint); B = lin.m_CenterPoint.distanceTo(lin.m_StartPoint); a = m_CenterPoint.X; b = m_CenterPoint.Y; c = lin.m_CenterPoint.X; d = lin.m_CenterPoint.Y; P = ((A * A - B * B) - (a * a + b * b - c * c - d * d)) / (2 * d - 2 * b); Q = (c - a) / (d - b); AA = 1 + Q * Q; BB = 2 * b * Q - 2 * P * Q - 2 * a; CC = P * P - 2 * b * P - A * A + a * a + b * b; if (BB * BB - 4 * AA * CC > 0) { X1 = (BB * -1 + Math.Sqrt(BB * BB - 4 * AA * CC)) / (2 * AA); X2 = (BB * -1 - Math.Sqrt(BB * BB - 4 * AA * CC)) / (2 * AA); Y1 = P - Q * X1; Y2 = P - Q * X2; ptInt1.X = X1; ptInt1.Y = Y1; ptInt2.X = X2; ptInt2.Y = Y2; nRet = 2; } else { nRet = 0; } } return(nRet); }
/// <summary> /// Calculates the bounding box. /// </summary> /// <param name="graphics">The graphics.</param> /// <param name="font">The font.</param> /// <param name="location">The location.</param> /// <param name="scale">The scale.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public RectangleF Layout(Graphics graphics, Font font, PointF location, float scale) => throw new NotImplementedException();