In UITextfield, When applying color using NSMutableAttributedString the color is not applied correctly when unfocusing - xamarin

Using NSMutableAttributedString, I applied color for a specific character in a string using UITextfield. My Code:
uITextField = new UITextField(); uITextField.BackgroundColor = UIColor.LightGray;
uITextField.Frame = new CGRect(10, 150, 350, 40);
uITextField.Text = "Hai i am ________________";
uITextField.TextColor = UIColor.Green;
uITextField.EditingChanged += UITextField_EditingChanged;
private void UITextField_EditingChanged(object sender, EventArgs e)
{
var promptStringAttributes = new UIStringAttributes
{
ForegroundColor = UIColor.Red
};
var promptString = new NSMutableAttributedString(uITextField.Text);
char[] mText = uITextField.Text.ToCharArray();
Char prchar = '_';
for (int i = 0; i < mText.Length; i++)
{
if (!string.IsNullOrEmpty(uITextField.Text) && prchar == mText[i])
{
promptString.SetAttributes(promptStringAttributes.Dictionary, new NSRange(i, 1));
}
}
uITextField.AttributedText = promptString;
}
Initially, the text will be in Green color. See the below image:
After deleting the last character in the UItextfield, I will change the color of some character to red
The problem which I am facing is after unfocusing the UITextfield, the Red color is applied to all the character in the UITextField and the text color is not displayed correctly. Only the set attribute color is applied for all the character in the string. See the below image:
Please give a possible solution to restrict of applying the set attribute color for all the string when unfocusing the UITextField in xamarin iOS.

Improve your method
var promptStringAttributes_Red = new UIStringAttributes
{
ForegroundColor = UIColor.Red
};
var promptStringAttributes_Green = new UIStringAttributes
{
ForegroundColor = UIColor.Green
};
var promptString = new NSMutableAttributedString(uITextField.Text);
char[] mText = uITextField.Text.ToCharArray();
Char prchar = '_';
for (int i = 0; i < mText.Length; i++)
{
if (!string.IsNullOrEmpty(uITextField.Text) && mText[i] ==prchar)
{
promptString.SetAttributes(promptStringAttributes_Red.Dictionary, new NSRange(i, 1));
}
else
{
promptString.SetAttributes(promptStringAttributes_Green.Dictionary, new NSRange(i, 1));
}
}
uITextField.AttributedText = promptString;

Related

dynamically change an image via c# script in Xamarin forms

I have a cross platform app which I need to show a set of images when the user clic in a button, so, I put these image files named as "img000.png" to "img029.png" in a folder in the PCL solution and make al these images as "EmbeddedResource", after,I fill a List with all these images and its work fine at now, i.e. the image is shown like I want, but when I click in the button to show the next image in the list the image don't go to the next.
I have this:
//...
public class ImageSetPage : BasePage
// BasePage encapsule a ContentPage...
{
private string directory = "MyApp.Assets.";
private int idx = 0;
protected StackLayout _mainLayout;
protected StackLayout _buttonStack;
protected Image _btnPrevI;
protected Label _displayName;
protected Image _btnNestI;
protected Image _image;
protected List<Image> _Images;
public ImageSetPage()
{
this._Images = getImages();
var prevI_Tap = new TapGestureRecognizer();
prevI_Tap.Tapped += (s, e) =>
{
onClick("pvi");
};
var nextI_Tap = new TapGestureRecognizer();
nextI_Tap.Tapped += (s, e) =>
{
onClick("nti");
};
/// begin layout
base.Title = "set of Images";
this._mainLayout = new StackLayout()
{
Orientation = StackOrientation.Vertical,
BackgroundColor = Color.Black,
Padding = new Thickness(0, 10, 0, 0)
};
this._btnPrevI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory+"prevbtn.png")
};
_btnPrevI.GestureRecognizers.Add(prevI_Tap);
this._displayName = new Label()
{
Style = Device.Styles.SubtitleStyle,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
TextColor = Color.White,
};
this._btnNextI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory + "nextbtn.png")
};
_btnNextI.GestureRecognizers.Add(nextI_Tap);
this._buttonStack.Children.Add(_btnPrevI);
this._buttonStack.Children.Add(_displayName);
this._buttonStack.Children.Add(_btnNextI);
this._mainLayout.Children.Add(_buttonStack);
FillImage(idx);
this._mainLayout.Children.Add(this._image);
this.Content = this._mainLayout;
}
private void FillImage(int i)
{
this._displayName.Text = "Image n# " + FillWithZeroes(i);
// [EDIT 1] cemented these lines ...
// this._image = null;
// mi = _images[i];
// this._image = mi;
// [EDIT 2] the new try
string f = directory + "imgs.img0" + FillWithZeroes(i) + ".png";
this._image = new Image() {
VerticalOptions = LayoutOptions.Center,
Soruce = ImageSource.FromResource(f)
};
// In this way the image show and don't change when click
// this Fking* code is a big S_OF_THE_B*
// The Xamarin and the C# is brothers of this FKing* code
}
private void onClick(string v)
{
string vw = v;
if (vw.Equals("pvi")) idx--;
if (vw.Equals("nti")) idx++;
if (idx <= 0) idx = 29;
if (idx >= 29) idx = 0;
FillImage(idx);
vw = "";
}
private string FillWithZeroes(int v)
{
string s = v.ToString();
string r = "";
if (s.Length == 1) { r = "0" + s; } else { r = s; }
return r;
}
// to fill a list of Images with files in a PCL folder
private List<Image> getImages()
{
string directory = "MyApp.Assets.";
List<Image> imgCards = new List<Image>();
int c = 0;
for (c = 0; c < 30;c++) {
string f = directory + "imgs.img0" + FillWithZeroes(c) + ".png";
Image img = new Image();
img.Source = ImageSource.FromResource(f);
imgCards.Add(img);
}
return imgCards;
}
// ...
}
but the image don't change, i.e. change, like I see in debug, but don't show in the Layout when I click in the buttons.
Maybe I'm doing it wrong.
Can someone here help me?
thanks in advance

How to create barcode image with ZXing.Net and ImageSharp in .Net Core 2.0

I'm trying to generate a barcode image. When I use the following code I can create a base64 string but it's giving a blank image. I checked the content is not blank or white space.
There are codes using CoreCompat.System.Drawing but I couldn't make it work because I am working in OS X environment.
Am I doing something wrong?
code:
[HtmlTargetElement("barcode")]
public class BarcodeHelper: TagHelper {
public override void Process(TagHelperContext context, TagHelperOutput output) {
var content = context.AllAttributes["content"].Value.ToString();
var alt = context.AllAttributes["alt"].Value.ToString();
var width = 250;
var height = 250;
var margin = 0;
var barcodeWriter = new ZXing.BarcodeWriterPixelData {
Format = ZXing.BarcodeFormat.CODE_128,
Options = new QrCodeEncodingOptions {
Height = height, Width = width, Margin = margin
}
};
var pixelData = barcodeWriter.Write(content);
using (var image = Image.LoadPixelData<Rgba32>(pixelData.Pixels, width, height))
{
output.TagName = "img";
output.Attributes.Clear();
output.Attributes.Add("width", width);
output.Attributes.Add("height", height);
output.Attributes.Add("alt", alt);
output.Attributes.Add("src", string.Format("data:image/png;base64,{0}", image.ToBase64String(ImageFormats.Png)));
}
}
}
There are some code snippets like below. They can write the content and easily convert the result data to base64 string. But when I call BarcodeWriter it needs a type <TOutput> which I don't know what to send. I am using ZXing.Net 0.16.2.
var writer = BarcodeWriter // BarcodeWriter without <TOutput> is missing. There is BarcodeWriter<TOutput> I can call.
{
Format = BarcodeFormat.CODE_128
}
var result = writer.write("content");
The current version (0.16.2) of the pixel data renderer uses a wrong alpha channel value. The whole barcode is transparent.
Additionally with my version of ImageSharp I had to remove the following part "data:image/png;base64,{0}", because image.ToBase64String includes this already.
Complete modified code:
[HtmlTargetElement("barcode")]
public class BarcodeHelper: TagHelper {
public override void Process(TagHelperContext context, TagHelperOutput output) {
var content = context.AllAttributes["content"].Value.ToString();
var alt = context.AllAttributes["alt"].Value.ToString();
var width = 250;
var height = 250;
var margin = 0;
var barcodeWriter = new ZXing.BarcodeWriterPixelData {
Format = ZXing.BarcodeFormat.CODE_128,
Options = new EncodingOptions {
Height = height, Width = width, Margin = margin
},
Renderer = new PixelDataRenderer {
Foreground = new PixelDataRenderer.Color(unchecked((int)0xFF000000)),
Background = new PixelDataRenderer.Color(unchecked((int)0xFFFFFFFF)),
}
};
var pixelData = barcodeWriter.Write(content);
using (var image = Image.LoadPixelData<Rgba32>(pixelData.Pixels, width, height))
{
output.TagName = "img";
output.Attributes.Clear();
output.Attributes.Add("width", pixelData.Width);
output.Attributes.Add("height", pixelData.Height);
output.Attributes.Add("alt", alt);
output.Attributes.Add("src", string.Format( image.ToBase64String(ImageFormats.Png)));
}
}
}
It's also possible to use the ImageSharp binding package (ZXing.Net.Bindings.ImageSharp).
[HtmlTargetElement("barcode")]
public class BarcodeHelper: TagHelper {
public override void Process(TagHelperContext context, TagHelperOutput output) {
var content = context.AllAttributes["content"].Value.ToString();
var alt = context.AllAttributes["alt"].Value.ToString();
var width = 250;
var height = 250;
var margin = 0;
var barcodeWriter = new ZXing.ImageSharp.BarcodeWriter<Rgba32> {
Format = ZXing.BarcodeFormat.CODE_128,
Options = new EncodingOptions {
Height = height, Width = width, Margin = margin
}
};
using (var image = barcodeWriter.Write(content))
{
output.TagName = "img";
output.Attributes.Clear();
output.Attributes.Add("width", image.Width);
output.Attributes.Add("height", image.Height);
output.Attributes.Add("alt", alt);
output.Attributes.Add("src", string.Format( image.ToBase64String(ImageFormats.Png)));
}
}
}

ChartControl - How to plot a line on X Axis (x - fixed coordinate, y - infinity)

I'm developing a C# winforms application in which I want to plot lines on X axis such that the X coordinate is a fixed value, but there is no Y coordinate specified.
Something like this:
Can this be done?
Stripline did the trick!
Here's the code:
public Series series1 = new Series
{
Name = "Series1",
Color = Color.Black,
IsVisibleInLegend = false,
ChartType = SeriesChartType.Line,
BorderWidth = 0,
XValueType = ChartValueType.Double,
YValueType = ChartValueType.Double
};
public StripLine startPositionLine = new StripLine
{
BorderColor = Color.Red,
BorderWidth = 2,
IntervalOffset = 7
};
public StripLine endPositionLine = new StripLine
{
BorderColor = Color.Blue,
BorderWidth = 2,
IntervalOffset = 11
};
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Interval = 1;
//Apparently some series with some points have to be present on the chart before the striplines get displayed
series1.Points.AddXY(0, 0);
series1.Points.AddXY(10, 0);
chart1.Series.Add(series1);
chart1.ChartAreas[0].AxisX.StripLines.Add(startPositionLine);
chart1.ChartAreas[0].AxisX.StripLines.Add(endPositionLine);
chart1.Invalidate();
}
And here's how the striplines are plotted:
One thing I need to check is whether or not a series needs to be plotted first before a stripline can be plotted.

Visifire.Charts How to disable vertical lines. WP

Chart is created by code. But I can't disable vertical lines in chart.
It is a code of creating chart:
public void CreateChart() {
CleanChart();
visiChart = new Chart()
{
ToolTipEnabled = true,
Width = 400,
Height = 200,
Padding = new Thickness(0),
Margin = new Thickness(0, 6, 0, -12),
Background = new SolidColorBrush(Colors.White),
};
ChartGrid grid = new ChartGrid()
{
Enabled = false
};
DataSeries dataSeries = new DataSeries();
DataPoint dataPoint;
Axis yAx = new Axis()
{
AxisLabels = new AxisLabels() { Enabled = false },
Grids = new ChartGridCollection() {grid}
};
int i = 0;
var deps = App.CurrentAgreement.Deposits.Deposit.Where(x => x.DepositIliv + x.DepositLink > 0).ToList();
foreach (var dep in deps) {
dataPoint = new DataPoint();
dataPoint.YValue = dep.DepositIliv + dep.DepositLink + dep.UValue + dep.WarrantyValue;
dataPoint.XValue = i;
i++;
dataPoint.LabelText = dataPoint.YValue.Out();
dataPoint.AxisXLabel = DateTime.Parse(dep.DepositDate).ToString("MMM yyyy");
dataPoint.MouseLeftButtonUp += dataPoint_MouseLeftButtonUp;
dataSeries.DataPoints.Add(dataPoint);
}
dataSeries.LabelEnabled = true;
dataSeries.RenderAs = RenderAs.Column;
dataSeries.Color = new SolidColorBrush(Colors.Green);
visiChart.Series.Add(dataSeries);
visiChart.AxesY.Add(yAx);
ChartPlaceHolder.Children.Add(visiChart);
}
But i dont need vertical lines visible. It is a screen of chart.
How i can disable lines??
Help me, please.
You have to disable the Grid lines from AxisX also.
Example:
ChartGrid grid = new ChartGrid()
{
Enabled = false
};
Axis xAx = new Axis();
xAx.Grids.Add(grid);
visiChart.AxesX.Add(xAx);

Datagridview - drawing rectangle on datagridview problem c# windows forms

I have 3 questions:
wheter I am doing my task in a good way
why when I scroll dataGridView, painted rectangles dissapear..
why painting is so slow...
Here is the code in which I want to draw a colorful rectangle with text on groups of cells in each column, that have the same values, empty values shouldn't have rectangles
void DataGridView1CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
foreach (DataGridViewColumn column in this.dataGridView1.Columns){
string tempCellValue = string.Empty;
int tempRectX = -1;
int tempRectY = -1;
int tempRectYEnd = -1;
int tempRectWidth = -1;
int tempRectHeight = -1;
foreach (DataGridViewRow row in this.dataGridView1.Rows){
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(
column.Index, row.Index,true);
DataGridViewCell cell = dataGridView1.Rows[row.Index].Cells[column.Index];
if ( cell.Value!=null){
if (tempRectX==-1){
tempRectX = rect.Location.X;
tempRectY = rect.Location.Y;
tempCellValue = cell.Value.ToString();
}else
if (cell.Value.ToString()!=tempCellValue){
tempRectYEnd = rect.Location.Y;
Rectangle newRect = new Rectangle(tempRectX,
tempRectY , 5 ,
tempRectYEnd );
using (
Brush gridBrush = new SolidBrush(Color.Coral),
backColorBrush = new SolidBrush(Color.Coral))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush,newRect);
} }
tempRectX=-1;
tempCellValue = string.Empty;
}
}else if (tempRectX!=-1){
tempRectYEnd = rect.Location.Y;
Rectangle newRect = new Rectangle(tempRectX,
tempRectY , 50 ,
tempRectYEnd );
using (
Brush gridBrush = new SolidBrush(Color.Coral),
backColorBrush = new SolidBrush(Color.Coral))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush,newRect);
} }
tempRectX=-1;
tempCellValue = string.Empty;
}
}}
The DataGridView1CellPainting event is intended to Paint or change Paint behaviour for one cell.
DGV raises this event for each visible Cell.
When Paint other cells, your code slow down.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellpaintingeventargs.aspx

Resources