I'm generating barcodes using ZXing.NET with this code
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
So currently each barcode (and with text) is just black. Is there a way I can pass in a Color object to colorize the barcode and text red for example? I tried this hacky solution to get the current pixel color, check if it's white and if not, colorize it to the specified font color.
for (int x = 0; x < barCodeBitmap.Width; x++)
{
for (int y = 0; y < barCodeBitmap.Height; y++)
{
Color currentColor = barCodeBitmap.GetPixel(x, y);
bool isWhite = currentColor == Color.White;
if (!isWhite) // this pixel should get a new color
{
barCodeBitmap.SetPixel(x, y, fontColor); // set a new color
}
}
}
Unfortunately each pixel gets colorized..
For colorizing the whole code (including the text) you can use the following snippet:
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat,
Options = new EncodingOptions
{
Width = barCodeWidth,
Height = barCodeHeight,
PureBarcode = !GenerateBarCodeWithText
},
Renderer = new BitmapRenderer
{
Foreground = Color.Red
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(content);
If you want different colors for the barcode and the text you have to write your own renderer implementation and use this instead of the BitmapRenderer.
You can take a look at the sources of BitmapRenderer and use it as a template for your own implementation:
https://github.com/micjahn/ZXing.Net/blob/master/Source/lib/renderer/BitmapRenderer.cs
Add a new property "TextColor" for example and use it in the line
var brush = new SolidBrush(Foreground);
changed to
var brush = new SolidBrush(TextColor);
Related
I wish to colour my OxyPlot's RectangleAnnotation with something more pretty than just a plain colour, i.e. some type of brush (GradientBrush etc.). I am working in WPF.
This question (PlotAreaBackground can be defined using gradient ?) on their GitHub site suggests that an annotation can be given a gradient, but I cannot find the suggested example.
Is there a way of applying a brush to a RectangleAnnotation? or any other way of creating coloured areas on a graph that are linked to the values on the axis?
I think that this is the suggested example.
I've modified it to look like a rectangle annotation, because the example fills the entire background. Hope it helps.
Efect:
Code:
// create a gradient image of height n
int n = 256;
var imageData1 = new OxyColor[n, 1];
for (int i = 0; i < n; i++)
{
imageData1[i, 0] = OxyColor.Interpolate(OxyColors.Red, OxyColors.Blue, i / (n - 1.0));
}
PngBitmapEncoder encoder = new PngBitmapEncoder();
PngEncoder encode = new PngEncoder(new PngEncoderOptions());
var image1 = new OxyImage(encode.Encode(imageData1));
ImageAnnotation anotation = new ImageAnnotation
{
ImageSource = image1,
Interpolate = true,
Layer = AnnotationLayer.BelowAxes,
X = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea),
Y = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea),
Width = new PlotLength(0.1, PlotLengthUnit.RelativeToPlotArea),
Height = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top
};
plotModel.Annotations.Add(anotation);
I have made an application which generates me a QR Code in a PNG image, but now I have to insert the text from QR Code next to the QR Code image.
I don't have any experience using ZXing Library but I'm thinking that it may contain an option for this...
Example:
Code:
namespace QR_Code_with_WFA
{
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
}
}
Well, ZXing.BarcodeWriter.Options has property PureBarcode, which will put source text into generated image when set to false.
Unfortunately it has no effect when format of barcode is BarcodeFormat.QR_CODE (and it is by design).
But you can draw your text manually after you've generated barcode image:
var result = qrcoder.Write(inputData);
using (var g = Graphics.FromImage(result))
using (var font = new Font(FontFamily.GenericMonospace, 12))
using (var brush = new SolidBrush(Color.Black))
using(var format = new StringFormat(){Alignment = StringAlignment.Center})
{
int margin = 5, textHeight = 20;
var rect = new RectangleF(margin, result.Height - textHeight,
result.Width - 2 * margin, textHeight);
g.DrawString(inputData, font, brush, rect, format);
}
result.Save(tempFileName);
Note you can select your own font size and fontfamily which will better suite your goals.
Update:
In the case you're trying to place text to the right from image - you have to "extend" to the right your generated image first, and then draw text:
var result = qrcoder.Write(inputData);
int textWidth = 200, textHeight = 20;
// creating new bitmap having imcreased width
var img = new Bitmap(result.Width + textWidth, result.Height);
using (var g = Graphics.FromImage(img))
using (var font = new Font(FontFamily.GenericMonospace, 12))
using (var brush = new SolidBrush(Color.Black))
using (var bgBrush = new SolidBrush(Color.White))
using (var format = new StringFormat() { Alignment = StringAlignment.Near })
{
// filling background with white color
g.FillRectangle(bgBrush, 0, 0, img.Width, img.Height);
// drawing your generated image over new one
g.DrawImage(result, new Point(0,0));
// drawing text
g.DrawString(inputData, font, brush, result.Width, (result.Height - textHeight) / 2, format);
}
img.Save(tempFileName);
I am working on zedgraph and generating a horizontal bar graph. I only want to know if there is any way by which each single bar can be made of different color. The output of the code is acceptable, I only intend on changing the color of the bars being generated. Any help would be much appreciated. Thanks!
myPane.YAxis.Title.Text = "Nominees";
myPane.XAxis.Title.Text = "Votes";
// Make up some random data points
string[] labels= new string[count];
for (int i = count-1; i >= 0; i--)
{
labels[counter] = voternames[i];
counter++;
}
for (int i = count1-1; i >= 0; i--)
{
y0[counter1] = Convert.ToDouble(votes[i]);
counter1++;
}
// Generate a red bar with "Curve 1" in the legend
BarItem myBar = myPane.AddBar("", y0, null, Color.Green);
// Draw the X tics between the labels instead of
// at the labels
myPane.YAxis.MajorTic.IsBetweenLabels = false;
// Set the XAxis labels
myPane.YAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.YAxis.Type = AxisType.Text;
myPane.BarSettings.Base = BarBase.Y;
// Fill the Axis and Pane backgrounds
myPane.Fill = new Fill(Color.FromArgb(250, 250, 255));
// Tell ZedGraph to refigure the
// axes since the data have changed
zgc.AxisChange();
zgc.Refresh();
Found what I was looking for, the original link to source is:
http://www.ironpython.info/index.php?title=Multi-colored_Bar_Chart_with_ZedGraph. The main modification was making a Point pair list instead of sending the double array for creating bars, giving reference to color array and setting min and max range for fills. The modified code is as follows:
myPane.YAxis.Title.Text = "Nominees";
myPane.XAxis.Title.Text = "Votes";
// Make up some random data points
string[] labels= new string[count];
//string[] labelx = new string[count];
for (int i = count-1; i >= 0; i--)
{
labels[counter] = voternames[i];
counter++;
}
for (int i = count1-1; i >= 0; i--)
{
y0[counter1] = Convert.ToDouble(votes[i]);
counter1++;
}
for (int i = 0; i < y0.Length; i++)
{
//Adding the x axis data and using y axis as a source to color a single bar
list.Add(y0[i], i / 2.0);
}
Color[] colors = new Color[] {Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Purple};
// Generate a bar with point pair list in the legend
BarItem myBar = myPane.AddBar("", list, Color.Green);
// Giving ref of color array
myBar.Bar.Fill = new Fill(colors);
//Setting to fill with using point values of y axis
myBar.Bar.Fill.Type = FillType.GradientByY;
//Setting min and max range is important
myBar.Bar.Fill.RangeMin = 0;
myBar.Bar.Fill.RangeMax = Convert.ToInt32(y0[0]);
// Draw the X tics between the labels instead of
// at the labels
myPane.YAxis.MajorTic.IsBetweenLabels = false;
// Set the XAxis labels
myPane.YAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.YAxis.Type = AxisType.Text;
myPane.BarSettings.Base = BarBase.Y;
// Fill the Axis and Pane backgrounds
//myPane.Chart.Fill = new Fill(Color.White,Color.FromArgb(255, 255, 166), 90F);
myPane.Fill = new Fill(Color.FromArgb(250, 250, 255));
// Tell ZedGraph to refigure the
// axes since the data have changed
zgc.AxisChange();
zgc.Refresh();
This question already has answers here:
Drawing a Rotated Text to an Image in C#
(2 answers)
Closed 7 years ago.
I have made an application which generates me a QR Code in a PNG image, and prints out the text from QR image, but now I need to rotate that text 90 degrees and I can't find a way to do this...I think that the rectangle must be rotated because the text it's inside this rectangle.
Example:
Code:
namespace QR_Code_with_WFA
{
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
var result2 = qrcoder.Write(inputData);
int textWidth = 200, textHeight = 20;
// creating new bitmap having imcreased width
var img = new Bitmap(result2.Width + textWidth, result2.Height);
using (var g = Graphics.FromImage(img))
using (var font = new Font(FontFamily.GenericMonospace, 12))
using (var brush = new SolidBrush(Color.Black))
using (var bgBrush = new SolidBrush(Color.White))
using (var format = new StringFormat() { Alignment = StringAlignment.Near })
{
// filling background with white color
g.FillRectangle(bgBrush, 0, 0, img.Width, img.Height);
// drawing your generated image over new one
g.DrawImage(result, new Point(0,0));
// drawing text
g.DrawString(inputData, font, brush, result2.Width, (result2.Height - textHeight) / 2, format);
}
img.Save(tempFileName);
}
}
You need to apply a RotateTransform on the Graphics object before drawing the text:
// Change alignment to center so you don't have to do the math yourself :)
using (var format = new StringFormat() { Alignment = StringAlignment.Center })
{
...
// Translate to the point where you want the text
g.TranslateTransform(result2.Width, result2.Height / 2);
// Rotation happens around that point
g.RotateTransform(-90);
// Note that we draw on [0, 0] because we translated our coordinates already
g.DrawString(inputData, font, brush, 0, 0, format);
// When done, reset the transform
g.ResetTransform();
}
You have to rotate full Graphics:
https://msdn.microsoft.com/en-us/library/a0z3f662(v=vs.110).aspx
Similar topic:
Rotated text align in C#
I want to add borders and background color to my PdfFormField. Now background color is activated only after I write something to text field but before that it is just white. And I can't get borders to show up.
This is my code:
public void addField(PdfWriter writer, string name, int x, int y, int w, int h, PdfContentByte cb, int maxSize, string text, BaseFont font, int border)
{
Rectangle rec = new Rectangle(x, y-h, x+w, y);
// Change the font Widths
//BaseFont font = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
float fontSize = 12;
//int[] widths = font.Widths;
//for (int k = 0; k < widths.Length; k++)
//{
//if (widths[k] != 0)
//widths[k] = width;
//}
font.ForceWidthsOutput = true;
string all = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-*/+.,\"'():;,?./!$+=_{[]}&éèàêîâ";
//Color textColor = BaseColor.RED;
// Create the Acroform TextField
PdfFormField field = PdfFormField.CreateTextField(writer, PdfFormField.SINGLELINE, PdfFormField.PLAINTEXT, maxSize);
field.FieldName = name;
field.DefaultValueAsString = text;
//ield.GetTextField();
field.MKBackgroundColor = BaseColor.RED;
//field.BackgroundColor = new GrayColor(0.75f);
//field.BorderColor = GrayColor.GRAYBLACK;
//field.BorderWidth = 1;
//field.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
field.SetPage();
writer.AddAnnotation(field);
// Position the field on the page
field.SetWidget(rec, PdfAnnotation.HIGHLIGHT_INVERT);
// Create apperance so the field Size and font match what we want
PdfAppearance tp = cb.CreateAppearance(rec.Right-rec.Left, rec.Top-rec.Bottom);
PdfAppearance da = (PdfAppearance)tp.Duplicate;
da.SetFontAndSize(font, fontSize);
da.SetColorFill(BaseColor.RED);
field.DefaultAppearanceString = da;
// Fill the default value of the field
tp.BeginVariableText();
tp.SaveState();
tp.Rectangle(rec);
tp.Clip();
tp.NewPath();
tp.BeginText();
tp.SetFontAndSize(font, fontSize);
tp.SetColorFill(BaseColor.BLACK);
tp.SetTextMatrix(100,100);
tp.ShowText(all);
tp.SetTextMatrix(2,(rec.Top-rec.Bottom)/2-(fontSize*0.3f));
tp.ShowText(text);
tp.EndText();
tp.RestoreState();
tp.EndVariableText();
field.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
}
Use the following code i hope it works
PdfFormField field = .......;
field.setMKBorderColor(BaseColor.BLACK);
field.setMKBackgroundColor(BaseColor.BLUE);