Datagridview - drawing rectangle on datagridview problem c# windows forms - windows

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

Related

Xamarin: Unable to extract central square of photo in Android/iOS

I am trying to get an image using the camera. The image is to be 256x256 and I want it to come from the centre of a photo taken using the camera on a phone. I found this code at: https://forums.xamarin.com/discussion/37647/cross-platform-crop-image-view
I am using this code for Android...
public byte[] CropPhoto(byte[] photoToCropBytes, Rectangle rectangleToCrop, double outputWidth, double outputHeight)
{
using (var photoOutputStream = new MemoryStream())
{
// Load the bitmap
var inSampleSize = CalculateInSampleSize((int)rectangleToCrop.Width, (int)rectangleToCrop.Height, (int)outputWidth, (int)outputHeight);
var options = new BitmapFactory.Options();
options.InSampleSize = inSampleSize;
//options.InPurgeable = true; see http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html
using (var photoToCropBitmap = BitmapFactory.DecodeByteArray(photoToCropBytes, 0, photoToCropBytes.Length, options))
{
var matrix = new Matrix();
var martixScale = outputWidth / rectangleToCrop.Width * inSampleSize;
matrix.PostScale((float)martixScale, (float)martixScale);
using (var photoCroppedBitmap = Bitmap.CreateBitmap(photoToCropBitmap, (int)(rectangleToCrop.X / inSampleSize), (int)(rectangleToCrop.Y / inSampleSize), (int)(rectangleToCrop.Width / inSampleSize), (int)(rectangleToCrop.Height / inSampleSize), matrix, true))
{
photoCroppedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, photoOutputStream);
}
}
return photoOutputStream.ToArray();
}
}
public static int CalculateInSampleSize(int inputWidth, int inputHeight, int outputWidth, int outputHeight)
{
//see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
int inSampleSize = 1; //default
if (inputHeight > outputHeight || inputWidth > outputWidth) {
int halfHeight = inputHeight / 2;
int halfWidth = inputWidth / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > outputHeight && (halfWidth / inSampleSize) > outputWidth)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
and this code for iOS...
public byte[] CropPhoto(byte[] photoToCropBytes, Xamarin.Forms.Rectangle
rectangleToCrop, double outputWidth, double outputHeight)
{
byte[] photoOutputBytes;
using (var data = NSData.FromArray(photoToCropBytes))
{
using (var photoToCropCGImage = UIImage.LoadFromData(data).CGImage)
{
//crop image
using (var photoCroppedCGImage = photoToCropCGImage.WithImageInRect(new CGRect((nfloat)rectangleToCrop.X, (nfloat)rectangleToCrop.Y, (nfloat)rectangleToCrop.Width, (nfloat)rectangleToCrop.Height)))
{
using (var photoCroppedUIImage = UIImage.FromImage(photoCroppedCGImage))
{
//create a 24bit RGB image to the output size
using (var cGBitmapContext = new CGBitmapContext(IntPtr.Zero, (int)outputWidth, (int)outputHeight, 8, (int)(4 * outputWidth), CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst))
{
var photoOutputRectangleF = new RectangleF(0f, 0f, (float)outputWidth, (float)outputHeight);
// draw the cropped photo resized
cGBitmapContext.DrawImage(photoOutputRectangleF, photoCroppedUIImage.CGImage);
//get cropped resized photo
var photoOutputUIImage = UIKit.UIImage.FromImage(cGBitmapContext.ToImage());
//convert cropped resized photo to bytes and then stream
using (var photoOutputNsData = photoOutputUIImage.AsJPEG())
{
photoOutputBytes = new Byte[photoOutputNsData.Length];
System.Runtime.InteropServices.Marshal.Copy(photoOutputNsData.Bytes, photoOutputBytes, 0, Convert.ToInt32(photoOutputNsData.Length));
}
}
}
}
}
}
return photoOutputBytes;
}
I am struggling to work out exactly what the parameters are to call the function.
Currently, I am doing the following:
double cropSize = Math.Min(DeviceDisplay.MainDisplayInfo.Width, DeviceDisplay.MainDisplayInfo.Height);
double left = (DeviceDisplay.MainDisplayInfo.Width - cropSize) / 2.0;
double top = (DeviceDisplay.MainDisplayInfo.Height - cropSize) / 2.0;
// Get a square resized and cropped from the top image as a byte[]
_imageData = mediaService.CropPhoto(_imageData, new Rectangle(left, top, cropSize, cropSize), 256, 256);
I was expecting this to crop the image to the central square (in portrait mode side length would be the width of the photo) and then scale it down to a 256x256 image. But it never picks the centre of the image.
Has anyone ever used this code and can tell me what I need to pass in for the 'rectangleToCrop' parameter?
Note: Both Android and iOS give the same image, just not the central part that I was expecting.
Here are the two routines I used:
Android:
public byte[] ResizeImageAndCropToSquare(byte[] rawPhoto, int outputSize)
{
// Create object of bitmapfactory's option method for further option use
BitmapFactory.Options options = new BitmapFactory.Options();
// InPurgeable is used to free up memory while required
options.InPurgeable = true;
// Get the original image
using (var originalImage = BitmapFactory.DecodeByteArray(rawPhoto, 0, rawPhoto.Length, options))
{
// The shortest edge will determine the size of the square image
int cropSize = Math.Min(originalImage.Width, originalImage.Height);
int left = (originalImage.Width - cropSize) / 2;
int top = (originalImage.Height - cropSize) / 2;
using (var squareImage = Bitmap.CreateBitmap(originalImage, left, top, cropSize, cropSize))
{
// Resize the square image to the correct size of an Avatar
using (var resizedImage = Bitmap.CreateScaledBitmap(squareImage, outputSize, outputSize, true))
{
// Return the raw data of the resized image
using (MemoryStream resizedImageStream = new MemoryStream())
{
// Resize the image maintaining 100% quality
resizedImage.Compress(Bitmap.CompressFormat.Png, 100, resizedImageStream);
return resizedImageStream.ToArray();
}
}
}
}
}
iOS:
private const int BitsPerComponent = 8;
public byte[] ResizeImageAndCropToSquare(byte[] rawPhoto, int outputSize)
{
using (var data = NSData.FromArray(rawPhoto))
{
using (var photoToCrop = UIImage.LoadFromData(data).CGImage)
{
nint photoWidth = photoToCrop.Width;
nint photoHeight = photoToCrop.Height;
nint cropSize = photoWidth < photoHeight ? photoWidth : photoHeight;
nint left = (photoWidth - cropSize) / 2;
nint top = (photoHeight - cropSize) / 2;
// Crop image
using (var photoCropped = photoToCrop.WithImageInRect(new CGRect(left, top, cropSize, cropSize)))
{
using (var photoCroppedUIImage = UIImage.FromImage(photoCropped))
{
// Create a 24bit RGB image of output size
using (var cGBitmapContext = new CGBitmapContext(IntPtr.Zero, outputSize, outputSize, BitsPerComponent, outputSize << 2, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst))
{
var photoOutputRectangleF = new RectangleF(0f, 0f, outputSize, outputSize);
// Draw the cropped photo resized
cGBitmapContext.DrawImage(photoOutputRectangleF, photoCroppedUIImage.CGImage);
// Get cropped resized photo
var photoOutputUIImage = UIImage.FromImage(cGBitmapContext.ToImage());
// Convert cropped resized photo to bytes and then stream
using (var photoOutputNsData = photoOutputUIImage.AsPNG())
{
var rawOutput = new byte[photoOutputNsData.Length];
Marshal.Copy(photoOutputNsData.Bytes, rawOutput, 0, Convert.ToInt32(photoOutputNsData.Length));
return rawOutput;
}
}
}
}
}
}
}

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

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;

OpenXML- Set a slide layout for a slide in presentation

Here is the code i used to create the presentation.
What i'm trying here is to create a slide and insert shapes into it and attach the slide into already created presentation. That works fine.
My question is how i set the layout the of the inserted slide. what i mean slide layout here is
slideLayoutpart.SlideLayout = new SlideLayout() {
Type = SlideLayoutValues.VerticalTitleAndText
};
I want to set this layout to my Slide.
I had looked working with slidelayout HERE
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
uint drawingObjectId = 1;
// Construct the slide content.
// Specify the non-visual properties of the new slide.
NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
// Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
// Declare and instantiate the title shape of the new slide. TITLE SHAPE
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
drawingObjectId++;
// Specify the required shape properties for the title shape.
NonVisualShapeProperties nonVisualShapeProperties2;
ShapeProperties shapeProperties2;
CreateVisualProperties(out nonVisualShapeProperties2, out shapeProperties2,
PlaceholderValues.Title, drawingObjectId);
// Specify the text of the title shape.
TextBody titletextBody = CreateContent(slideTitle, PlaceholderValues.Title);
titleShape.Append(nonVisualShapeProperties2);
titleShape.Append(shapeProperties2);
titleShape.Append(titletextBody);
// Save the new slide part.
slide.Save(slidePart);
#region Slide Poistioning
// The slide ID list should not be null.
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
// Find the highest slide ID in the current list.
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
}
position--;
if (position == 0)
{
prevSlideId = slideId;
}
}
maxSlideId++;
// Get the ID of the previous slide.
SlidePart lastSlidePart;
if (prevSlideId != null)
{
//Changed to set first thing as layout
// lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
}
else
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
}
// Use the same slide LAYOUT HERE as that of the previous slide.
if (null != lastSlidePart.SlideLayoutPart)
{
SlideLayoutPart slideLayoutpartNew = lastSlidePart.SlideLayoutPart;
slideLayoutpartNew.AddNewPart<SlideMasterPart>();
slideLayoutpartNew.SlideLayout = new SlideLayout() { Type = SlideLayoutValues.VerticalTitleAndText };
slidePart.AddPart(slideLayoutpartNew);
slidePart.AddPart(slideLayoutPart);
//When i try to set lastslidelayout it works fine.
//slidePart.AddPart(lastSlidePart.SlideLayoutPart);
}
// Insert the new slide into the slide list after the previous slide.
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
#endregion
// Save the modified presentation.
presentationPart.Presentation.Save();
I figured out ,How to set layout
string layoutName = "Title and Content";
// Get SlideMasterPart and SlideLayoutPart from the existing Presentation Part
SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault
(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));
if (slideLayoutPart == null)
{
throw new Exception("The slide layout " + layoutName + " is not found");
}
slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
I'm here appending the layout to slidepart and will save the presentation

Unable to add an Image to a powerpoint presentation using open xml

I am using the following code to add a new slide to a ppt file and add an image. I am using Open XML 2.5 SDK.
A new slide is getting added but not the image. Is there anything wrong in this code?
int position = 1;
using (PresentationDocument presentationDocument = PresentationDocument.Open("c.pptx", true))
{
PresentationPart presentationPart = presentationDocument.PresentationPart;
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
// Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
// Create the slide part for the new slide.
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
// Save the new slide part.
slide.Save(slidePart);
string imgId = "rId" + new Random().Next(2000).ToString();
ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Png, imgId);
using (FileStream stream = new FileStream("a.png", FileMode.Open))
{
stream.Position = 0;
imagePart.FeedData(stream);
}
slide.Save(slidePart);
// Modify the slide ID list in the presentation part.
// The slide ID list should not be null.
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
// Find the highest slide ID in the current list.
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
}
position--;
if (position == 0)
{
prevSlideId = slideId;
}
}
maxSlideId++;
// Get the ID of the previous slide.
SlidePart lastSlidePart;
if (prevSlideId != null)
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
}
else
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
}
// Use the same slide layout as that of the previous slide.
if (null != lastSlidePart.SlideLayoutPart)
{
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
}
// Insert the new slide into the slide list after the previous slide.
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
// Save the modified prsentation.
presentationPart.Presentation.Save();
Thanks in advance.

How to create grid border?

This is what I'm trying to create. White areas are System.Windows.Shapes.Rectangle in a Grid. This is my code for creating grid, columns, rows and rectangles;
Grid newGrid = new Grid();
for(int r=0; r<10; r++ ) {
newGrid.RowDefinitions.Add(
new RowDefinition { Height = new GridLength(30) });
for( int c=0; c<10; c++ ) {
newGrid.ColumnDefinitions.Add(
new ColumnDefinition { Width = new GridLength(30) });
Rectangle rec = new Rectangle{
Fill = new SolidColorBrush(Colors.White)
};
Grid.SetColumn(rec, c);
Grid.SetRow(rec, r);
newGrid.Children.Add(rec);
}
}
LayoutRoot.Children.Add(newGrid);
But I have not any idea how can add borders as we can see in picture. Thanks for suggestions.
Try
SolidColorBrush blackBrush = new SolidColorBrush();
blackBrush.Color = Colors.Black;
rec.Stroke = blackBrush;

Resources