Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Калентьев Илья tg: @m1nus0ne #22

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions TagCloud/CloudDrawers/ICloudDrawer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Drawing;
using TagCloud;

namespace TagCloudTests;

public interface ICloudDrawer
{
void Draw(List<TextRectangle> rectangle);
}
57 changes: 57 additions & 0 deletions TagCloud/CloudDrawers/TagCloudDrawer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Drawing;
using TagCloud.Extensions;
using TagCloudTests;

namespace TagCloud;

public class TagCloudDrawer : ICloudDrawer
{
private readonly string path;
private readonly IColorSelector selector;
private readonly string name;
private readonly Font font;

private TagCloudDrawer(string path, string name, IColorSelector selector, Font font)
{
this.path = path;
this.selector = selector;
this.font = font;
this.name = name;
}

public void Draw(List<TextRectangle> rectangles)
{
if (rectangles.Count == 0)
throw new ArgumentException("Empty rectangles list");

var containingRect = rectangles
.Select(r => r.Rectangle)
.GetMinimalContainingRectangle();

using var bitmap = new Bitmap(containingRect.Width + 2, containingRect.Height + 2);
using var graphics = Graphics.FromImage(bitmap);

graphics.DrawStrings(
selector,
rectangles
.Select(rect => rect.OnLocation(-containingRect.X + rect.X, -containingRect.Y + rect.Y))
.ToArray()
);

SaveToFile(bitmap);
}

private void SaveToFile(Bitmap bitmap)
{
var pathToFile = @$"{path}\{name}";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сейчас это не так важно, потому, что код запуститься только на windows из-за зависимостей, но на будущее, для обьединения путей стоит использовать Path.Combine или хотя бы Path.PathSeparator

bitmap.Save(pathToFile);
Console.WriteLine($"Tag cloud visualization saved to file {path}");
}

public static TagCloudDrawer Create(string path, string name, Font font, IColorSelector selector)
{
if (!Directory.Exists(path))
throw new ArgumentException("Directory does not exist");
return new TagCloudDrawer(path, name, selector, font);
}
}
36 changes: 36 additions & 0 deletions TagCloud/CloudLayouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Drawing;

namespace TagCloud;

public class CloudLayouter
{
private List<Rectangle> rectangles;
private ICloudShaper shaper;

public IReadOnlyList<Rectangle> Rectangles => rectangles;

public CloudLayouter(ICloudShaper shaper)
{
rectangles = new List<Rectangle>();
this.shaper = shaper;
}

public Rectangle PutNextRectangle(Size size)
{
if (size.Width <= 0)
throw new ArgumentException("Size width must be positive number");
if (size.Height <= 0)
throw new ArgumentException("Size height must be positive number");

Rectangle rectangle = Rectangle.Empty;
foreach (var point in shaper.GetPossiblePoints())
{
rectangle = new Rectangle(point, size);
if (!Rectangles.Any(rect => rect.IntersectsWith(rectangle)))
break;
}

rectangles.Add(rectangle);
return rectangle;
}
}
8 changes: 8 additions & 0 deletions TagCloud/CloudSharper/ICloudShaper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Drawing;

namespace TagCloud;

public interface ICloudShaper
{
IEnumerable<Point> GetPossiblePoints();
}
53 changes: 53 additions & 0 deletions TagCloud/CloudSharper/SpiralCloudShaper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Drawing;

namespace TagCloud;

public class SpiralCloudShaper : ICloudShaper
{
private Point center;
private double coefficient;
private double deltaAngle;

private SpiralCloudShaper(Point center, double coefficient, double deltaAngle)
{
this.center = center;
this.deltaAngle = deltaAngle;
this.coefficient = coefficient;
}

public IEnumerable<Point> GetPossiblePoints()
{
var currentAngle = 0D;
var position = center;
var previousPoint = position;
while(true)
{
while (position == previousPoint)
{
currentAngle += deltaAngle;
previousPoint = position;
position = CalculatePointByCurrentAngle(currentAngle);
}
yield return position;
previousPoint = position;
position = CalculatePointByCurrentAngle(currentAngle);
}
}

private Point CalculatePointByCurrentAngle(double angle)
{
return new Point(
center.X + (int)(coefficient * angle * Math.Cos(angle)),
center.Y + (int)(coefficient * angle * Math.Sin(angle))
);
}

public static SpiralCloudShaper Create(Point center, double coefficient = 0.1, double deltaAngle = 0.1)
{
if (coefficient <= 0)
throw new ArgumentException("Spiral coefficient must be positive number");
if (deltaAngle <= 0)
throw new ArgumentException("Spiral delta angle must be positive number");
return new SpiralCloudShaper(center, coefficient, deltaAngle);
}
}
15 changes: 15 additions & 0 deletions TagCloud/ColorSelectors/ConstantColorSelector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Drawing;
using TagCloudTests;

namespace TagCloud;

public class ConstantColorSelector : IColorSelector
{
private Color color;
public ConstantColorSelector(Color color)
{
this.color = color;
}

public Color SetColor() => color;
}
14 changes: 14 additions & 0 deletions TagCloud/ColorSelectors/GrayScaleColorSelector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Drawing;

namespace TagCloudTests;

public class GrayScaleColorSelector : IColorSelector
{
private readonly Random random = new(DateTime.Now.Microsecond);

public Color SetColor()
{
var gray = random.Next(100, 200);
return Color.FromArgb(gray, gray, gray);
}
}
8 changes: 8 additions & 0 deletions TagCloud/ColorSelectors/IColorSelector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Drawing;

namespace TagCloudTests;

public interface IColorSelector
{
Color SetColor();
}
15 changes: 15 additions & 0 deletions TagCloud/ColorSelectors/RandomColorSelector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Drawing;

namespace TagCloud.ColorSelectors;

public class RandomColorSelector
{
private readonly Random random = new(DateTime.Now.Microsecond);

public Color SetColor()
{
var color = random.Next(0, 255);
return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}

}
22 changes: 22 additions & 0 deletions TagCloud/Extensions/ColorConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Drawing;
using System.Text.RegularExpressions;

namespace TagCloud.Extensions;

public static class ColorConverter
{
public static bool TryConvert(string hexString, out Color color)
{
color = default;
var colorHexRegExp = new Regex(@"^#([A-Fa-f0-9]{6})$");
if (colorHexRegExp.Count(hexString) != 1)
return false;
var rgbValue = hexString
.Replace("#", "")
.Chunk(2)
.Select(chars => Convert.ToInt32(new string(chars), 16))
.ToArray();
Comment on lines +14 to +18
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rgb коды могут задаваться 3 hex цифрами

color = Color.FromArgb(rgbValue[0], rgbValue[1], rgbValue[2]);
return true;
}
}
17 changes: 17 additions & 0 deletions TagCloud/Extensions/GraphicsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Drawing;
using TagCloudTests;

namespace TagCloud.Extensions;

public static class GraphicsExtensions
{
public static void DrawStrings(this Graphics graphics, IColorSelector selector, TextRectangle[] rectangles)
{
using var brush = new SolidBrush(selector.SetColor());
foreach (var rectangle in rectangles)
{
graphics.DrawString(rectangle.Text, rectangle.Font, brush, rectangle.X, rectangle.Y);
brush.Color = selector.SetColor();
}
}
}
11 changes: 11 additions & 0 deletions TagCloud/Extensions/PointExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Drawing;

namespace TagCloud.Extensions;

public static class PointExtension
{
public static double GetDistanceTo(this Point first, Point second)
{
return Math.Sqrt((first.X - second.X) * (first.X - second.X) + (first.Y - second.Y) * (first.Y - second.Y));
}
}
36 changes: 36 additions & 0 deletions TagCloud/Extensions/RectangleEnumerableExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Drawing;

namespace TagCloud.Extensions;

public static class RectangleEnumerableExtensions
{
public static bool HasIntersectedRectangles(this IEnumerable<Rectangle> rectangles)
{
return rectangles
.SelectMany(
(x, i) => rectangles.Skip(i + 1),
(x, y) => Tuple.Create(x, y)
)
.Any(tuple => tuple.Item1.IntersectsWith(tuple.Item2));
}

public static Rectangle GetMinimalContainingRectangle(this IEnumerable<Rectangle> rectangles)
{
int minX = int.MaxValue, minY = int.MaxValue;
int maxX = int.MinValue, maxY = int.MinValue;

foreach (var rectangle in rectangles)
{
if (rectangle.X < minX)
minX = rectangle.X;
if (rectangle.Y < minY)
minY = rectangle.Y;
if (rectangle.Right > maxX)
maxX = rectangle.Right;
if (rectangle.Bottom > maxY)
maxY = rectangle.Bottom;
}

return new Rectangle(minX, minY, maxX - minX, maxY- minY);
}
}
61 changes: 61 additions & 0 deletions TagCloud/Option.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using CommandLine;

namespace TagCloudApplication;

public class Options
{
[Option('d', "destination", HelpText = "Set destination path.", Default = @"..\..\..\Results")]
public string DestinationPath { get; set; }

[Option('s', "source", HelpText = "Set source path.", Default = @"..\..\..\Results\text.txt")]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Попробуй посмотреть описание любой часто используемой консольной программы, сдеалнное тобой описание не информативно

public string SourcePath { get; set; }

[Option('n', "name", HelpText = "Set name.", Default = "default.png")]
public string Name { get; set; }

[Option('c', "color",
HelpText = """
Set color.
random - Random colors
#F0F0F0 - Color hex code
""",
Default = "random")]
public string ColorScheme { get; set; }

[Option('f', "font", HelpText = "Set font.", Default = "Arial")]
public string Font { get; set; }

[Option("size", HelpText = "Set font size.", Default = 20)]
public int FontSize { get; set; }

[Option("unusedParts",
HelpText = """
Set unused parts of speech.
A - прилагательное
ADV - наречие
ADVPRO - местоименное наречие
ANUM - числительное-прилагательное
APRO - местоимение-прилагательное
COM - часть композита - сложного слова
CONJ - союз
INTJ - междометие
NUM - числительное
PART - частица
PR - предлог
S - существительное
SPRO - местоимение-существительное
V - глагол
""",
Default = new[] { "PR", "PART", "CONJ", "INTJ" })]
public string[] UnusedPartsOfSpeech { get; set; }

[Option("density", HelpText = "Set density.", Default = 0.1)]
public double Density { get; set; }

[Option("width", HelpText = "Set width.", Default = 100)]
public int Width { get; set; }


[Option("height", HelpText = "Set height.", Default = 100)]
public int Height { get; set; }
}
3 changes: 3 additions & 0 deletions TagCloud/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// See https://aka.ms/new-console-template for more information

Console.WriteLine("Hello, World!");
Loading