XNA multiples cubes - c#

firstly, forgive my English, I'm French...
I wrote a code that does not work.
I want to draw a mutliples blocks, like Minecraft, but in Voxel.
on one side of my map, the result is good:
This render is opaque, good !
but on the other side, I get this:
But in this side of my map, it's no good :(
Some faces appear through some other faces...
Who has an idea ? My Normals ?
My function Remake() is not used, it's for remove faces...
namespace LandOfCube.Models
{
class Block
{
VertexBuffer instanceBuffer;
public enum Form
{
all,
noUp,
noDown,
noRight,
noLeft,
noFront,
noBack
}
public Form cubeForm = Form.all;
GraphicsDevice Graphics;
Effect shader;
private VertexBuffer vb;
Color CubeColor;
public Vector3 pos;
VertexPositionColorNormal[] vertices;
VertexPositionColorNormal[] verticesNoUp;
VertexPositionColorNormal[] verticesNoDown;
VertexPositionColorNormal[] verticesNoFront;
VertexPositionColorNormal[] verticesNoBack;
VertexPositionColorNormal[] verticesNoRight;
VertexPositionColorNormal[] verticesNoLeft;
private VertexPositionColorNormal[] Front = new VertexPositionColorNormal[5];
private VertexPositionColorNormal[] Back = new VertexPositionColorNormal[5];
private VertexPositionColorNormal[] Right = new VertexPositionColorNormal[5];
private VertexPositionColorNormal[] Up = new VertexPositionColorNormal[5];
private VertexPositionColorNormal[] Left = new VertexPositionColorNormal[5];
private VertexPositionColorNormal[] Down = new VertexPositionColorNormal[5];
public Vector3 normalFront = Vector3.Forward;
public Vector3 normalBack = Vector3.Backward;
public Vector3 normalTop = Vector3.Up;
public Vector3 normalBottom = Vector3.Down;
public Vector3 normalLeft = Vector3.Left;
public Vector3 normalRight = Vector3.Right;
public Block(GraphicsDevice graph, Color color, Vector3 position, ContentManager content)
{
Graphics = graph;
shader = content.Load<Effect>("effects");
CubeColor = color;
pos = position;
Init();
SetVertices();
}
bool test = false;
public void Draw(Camera camera)
{
Graphics.SetVertexBuffer(vb);
shader.CurrentTechnique = shader.Techniques["Colored"];
shader.Parameters["xView"].SetValue(camera.View);
shader.Parameters["xProjection"].SetValue(camera.Projection);
shader.Parameters["xWorld"].SetValue(Matrix.Identity);
Vector3 lightDirection = new Vector3(1.0f, -1.0f, -1.0f);
lightDirection.Normalize();
shader.Parameters["xLightDirection"].SetValue(lightDirection);
shader.Parameters["xAmbient"].SetValue(0.1f);
shader.Parameters["xEnableLighting"].SetValue(true);
foreach (EffectPass pass in shader.CurrentTechnique.Passes)
{
pass.Apply();
this.Graphics.DrawPrimitives(PrimitiveType.TriangleList, 0, vertices.Length / 3);
}
}
#region Methode abstraites
private void Init()
{
InitFront();
InitBack();
InitDown();
InitUp();
InitLeft();
InitRight();
}
public void Remake()
{
switch (cubeForm)
{
case Form.noBack:
vertices = verticesNoBack;
break;
case Form.noFront:
vertices = verticesNoFront;
break;
case Form.noUp:
vertices = verticesNoUp;
break;
case Form.noDown:
vertices = verticesNoDown;
break;
case Form.noRight:
vertices = verticesNoRight;
break;
case Form.noLeft:
vertices = verticesNoLeft;
break;
}
vb = new VertexBuffer(Graphics, typeof(VertexPositionColorNormal), vertices.Length, BufferUsage.None);
vb.SetData(vertices);
verticesNoBack = null;
verticesNoDown = null;
verticesNoFront = null;
verticesNoLeft = null;
verticesNoRight = null;
verticesNoUp = null;
test = true;
}
public void SetVertices()
{
this.vertices = new VertexPositionColorNormal[36];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
setNoBack();
setNoFront();
setNoUp();
setNoDown();
setNoRight();
setNoLeft();
vb = new VertexBuffer(Graphics, typeof(VertexPositionColorNormal), vertices.Length, BufferUsage.None);
vb.SetData(vertices);
Clean();
}
#region InitFaces
public void setNoBack()
{
this.verticesNoBack = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
}
public void setNoFront()
{
this.verticesNoFront = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
}
public void setNoUp()
{
this.verticesNoUp = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
}
public void setNoDown()
{
this.verticesNoFront = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
}
public void setNoLeft()
{
this.verticesNoLeft = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Right[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
}
public void setNoRight()
{
this.verticesNoRight = new VertexPositionColorNormal[30];
int y = 0;
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Up[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Down[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Back[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Front[x]; y++;
}
for (int x = 0; x < 6; x++)
{
this.vertices[y] = Left[x]; y++;
}
}
public void InitFront()
{
this.Front = new VertexPositionColorNormal[6];
Front[0].Position = new Vector3(pos.X, pos.Y + 1, pos.Z);
Front[0].Color = Color.Blue;
Front[0].Normal = normalFront;
Front[1].Position = new Vector3(pos.X, pos.Y, pos.Z + 1);
Front[1].Color = Color.Blue;
Front[1].Normal = normalFront;
Front[2].Position = new Vector3(pos.X, pos.Y, pos.Z);
Front[2].Color = Color.Blue;
Front[2].Normal = normalFront;
Front[3].Position = new Vector3(pos.X, pos.Y + 1, pos.Z);
Front[3].Color = Color.Blue;
Front[3].Normal = normalFront;
Front[4].Position = new Vector3(pos.X, pos.Y + 1, pos.Z + 1);
Front[4].Color = Color.Blue;
Front[4].Normal = normalFront;
Front[5].Position = new Vector3(pos.X, pos.Y, pos.Z + 1);
Front[5].Color = Color.Blue;
Front[5].Normal = normalFront;
}
public void InitBack()
{
this.Back = new VertexPositionColorNormal[6];
Back[0].Position = new Vector3(pos.X + 1, pos.Y, pos.Z + 1);
Back[0].Color = Color.Red;
Back[0].Normal = normalBack;
Back[1].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Back[1].Color = Color.Red;
Back[1].Normal = normalBack;
Back[2].Position = new Vector3(pos.X + 1, pos.Y, pos.Z);
Back[2].Color = Color.Red;
Back[2].Normal = normalBack;
Back[3].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1);
Back[3].Color = Color.Red;
Back[3].Normal = normalBack;
Back[4].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Back[4].Color = Color.Red;
Back[4].Normal = normalBack;
Back[5].Position = new Vector3(pos.X + 1, pos.Y, pos.Z + 1);
Back[5].Color = Color.Red;
Back[5].Normal = normalBack;
}
public void InitUp()
{
this.Up = new VertexPositionColorNormal[6];
Up[0].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Up[0].Color = Color.Black;
Up[0].Normal = normalTop;
Up[1].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1);
Up[1].Color = Color.Black;
Up[1].Normal = normalTop;
Up[2].Position = new Vector3(pos.X, pos.Y + 1, pos.Z + 1);
Up[2].Color = Color.Black;
Up[2].Normal = normalTop;
Up[3].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Up[3].Color = Color.Black;
Up[3].Normal = normalTop;
Up[4].Position = new Vector3(pos.X, pos.Y + 1, pos.Z + 1);
Up[4].Color = Color.Black;
Up[4].Normal = normalTop;
Up[5].Position = new Vector3(pos.X, pos.Y + 1, pos.Z);
Up[5].Color = Color.Black;
Up[5].Normal = normalTop;
}
public void InitDown()
{
this.Down = new VertexPositionColorNormal[6];
Down[0].Position = new Vector3(pos.X + 1, pos.Y, pos.Z);
Down[0].Color = Color.Orange;
Down[0].Normal = normalBottom;
Down[1].Position = new Vector3(pos.X, pos.Y, pos.Z);
Down[1].Color = Color.Orange;
Down[1].Normal = normalBottom;
Down[2].Position = new Vector3(pos.X, pos.Y, pos.Z + 1);
Down[2].Color = Color.Orange;
Down[2].Normal = normalBottom;
Down[3].Position = new Vector3(pos.X + 1, pos.Y, pos.Z);
Down[3].Color = Color.Orange;
Down[3].Normal = normalBottom;
Down[4].Position = new Vector3(pos.X, pos.Y, pos.Z + 1);
Down[4].Color = Color.Orange;
Down[4].Normal = normalBottom;
Down[5].Position = new Vector3(pos.X + 1, pos.Y, pos.Z + 1);
Down[5].Color = Color.Orange;
Down[5].Normal = normalBottom;
}
public void InitRight()
{
this.Right = new VertexPositionColorNormal[6];
Right[0].Position = new Vector3(pos.X + 1, pos.Y, pos.Z + 1);
Right[0].Color = Color.Green;
Right[0].Normal = normalRight;
Right[1].Position = new Vector3(pos.X, pos.Y, pos.Z + 1);
Right[1].Color = Color.Green;
Right[1].Normal = normalRight;
Right[2].Position = new Vector3(pos.X, pos.Y + 1, pos.Z + 1);
Right[2].Color = Color.Green;
Right[3].Normal = normalRight;
Right[3].Position = new Vector3(pos.X + 1, pos.Y, pos.Z + 1);
Right[3].Color = Color.Green;
Right[3].Normal = normalRight;
Right[4].Position = new Vector3(pos.X, pos.Y + 1, pos.Z + 1);
Right[4].Color = Color.Green;
Right[4].Normal = normalRight;
Right[5].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1);
Right[5].Color = Color.Green;
Right[5].Normal = normalRight;
}
public void InitLeft()
{
this.Left = new VertexPositionColorNormal[6];
Left[0].Position = new Vector3(pos.X, pos.Y, pos.Z);
Left[0].Color = Color.Aqua;
Left[0].Normal = normalLeft;
Left[1].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Left[1].Color = Color.Aqua;
Left[1].Normal = normalLeft;
Left[2].Position = new Vector3(pos.X, pos.Y + 1, pos.Z);
Left[2].Color = Color.Aqua;
Left[2].Normal = normalLeft;
Left[3].Position = new Vector3(pos.X, pos.Y, pos.Z);
Left[3].Color = Color.Aqua;
Left[3].Normal = normalLeft;
Left[4].Position = new Vector3(pos.X + 1, pos.Y, pos.Z);
Left[4].Color = Color.Aqua;
Left[4].Normal = normalLeft;
Left[5].Position = new Vector3(pos.X + 1, pos.Y + 1, pos.Z);
Left[5].Color = Color.Aqua;
Left[5].Normal = normalLeft;
}
#endregion
private void setTriangleNormal(VertexPositionColorNormal v1, VertexPositionColorNormal v2, VertexPositionColorNormal v3)
{
Vector3 side1 = v1.Position - v3.Position;
Vector3 side2 = v1.Position - v2.Position;
Vector3 normal = Vector3.Cross(side1, side2);
v1.Normal += normal;
v2.Normal += normal;
v3.Normal += normal;
v1.Position.Normalize();
v1.Position.Normalize();
v1.Position.Normalize();
}
public void Clean()
{
Front = null;
Back = null;
Right = null;
Left = null;
Up = null;
Down = null;
}
#endregion
}
}

My guess is that you are winding the vertices on the back sides of the cubes in the wrong direction, making their normal point to the inside of the cube instead of the outside. One very common optimization in 3d code is to only draw triangles that have a normal facing the camera.

Related

DrawPolygon() erases the old polygon when drawing

I set the points and when the points of the same color form a square, I draw a polygon. But when a new square is formed, the old one disappears.
can you tell me how to make sure that when drawing a new polygon, the old one does not disappear?
in the checkpoint() function, I check whether there is a square of points of the same color and return e coordinates for drawing.
public partial class Form1 : Form
{
private Class1 Class1 = new Class1();
private CellState currentPlayer = CellState.Red;
public const int SIZE = 11;
public const int Icon_Size = 30;
public Form1()
{
InitializeComponent();
}
//ставит точки
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
var p = new Point((int)Math.Round(1f * e.X / Icon_Size), (int)Math.Round(1f * e.Y / Icon_Size));
if (Class1[p] == CellState.Empty)
{
Class1.SetPoint(p, currentPlayer);
currentPlayer = Class1.Inverse(currentPlayer);
Invalidate();
}
}
//рисуем
private void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(Icon_Size, Icon_Size);
//рисуем сеточку
using (var pen = new Pen(Color.Gainsboro, 0.1f))
{
for (int x = 1; x < SIZE; x++)
e.Graphics.DrawLine(pen, x, 1, x, SIZE - 1);
for (int y = 1; y < SIZE; y++)
e.Graphics.DrawLine(pen, 1, y, SIZE - 1, y);
}
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//рисуем точки
using (var brush = new SolidBrush(Color.White))
for (int x = 1; x < Form1.SIZE; x++)
for (int y = 1; y < Form1.SIZE; y++)
{
var p = new Point(x, y);
var cell = Class1[p];
if (cell != CellState.Empty)
{
brush.Color = StateToColor(cell);
e.Graphics.FillEllipse(brush, x - 0.2f, y - 0.2f, 0.4f, 0.4f);
}
}
using (var PenP = new Pen(Color.Black, 0.1f))
using (var brush = new SolidBrush(Color.White))
{
Class1.CheckPoint();
int i = Class1.CheckPoint()[0];
int j = Class1.CheckPoint()[1];
int cp = Class1.CheckPoint()[2];
if (cp == 1)
{
PenP.Color = Color.Red;
brush.Color = Color.IndianRed;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
if (cp == 2)
{
PenP.Color = Color.Blue;
brush.Color = Color.RoyalBlue;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
}
}
//условие смены цвета под ход игрока
Color StateToColor(CellState state, byte alpha = 255)
{
var res = state == CellState.Blue ? Color.Blue : Color.Red;
return Color.FromArgb(alpha, res);
}
}

Unity Planet Generator Colors not working

I am following this tutorial: https://www.youtube.com/watch?v=LyV7cEQyZMk to generate a planet for my game. I have gotten up to 6:08
For some reason, the color of the planet won't change depending on the type like it should, it is only white.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Type
{
Water, Ice, Volcano, Snow, Grass, Forest, Desert, Rocky
}
[CreateAssetMenu()]
public class PlanetSettings : ScriptableObject
{
public float Size;
public Type type;
}
public class TerrainFace
{
Mesh mesh;
int resolution;
Vector3 localUp;
Vector3 axisA;
Vector3 axisB;
Vector3[] vertices;
int[] triangles;
PlanetSettings settings;
Vector3 CalculatePointOnPlanet(Vector3 p)
{
return p * settings.Size;
}
public TerrainFace(Mesh mesh, int resolution, Vector3 localUp, PlanetSettings settings)
{
this.mesh = mesh;
this.resolution = resolution;
this.localUp = localUp;
this.settings = settings;
axisA = new Vector3(localUp.y, localUp.z, localUp.x);
axisB = Vector3.Cross(localUp, axisA);
}
public void ConstructMesh()
{
vertices = new Vector3[resolution * resolution];
triangles = new int[(resolution - 1) * (resolution - 1) * 6];
int triIndex = 0;
for (int y = 0; y < resolution; y++)
{
for (int x = 0; x < resolution; x++)
{
int index = x + y * resolution;
Vector2 percent = new Vector2(x, y) / (resolution - 1);
Vector3 pointOnUnitCube = localUp + (percent.x - 0.5f) * 2 * axisA + (percent.y - 0.5f) * 2 * axisB;
Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
vertices[index] = CalculatePointOnPlanet(pointOnUnitSphere);
if (x != resolution - 1 && y != resolution - 1)
{
triangles[triIndex] = index;
triangles[triIndex + 1] = index + resolution + 1;
triangles[triIndex + 2] = index + resolution;
triangles[triIndex + 3] = index;
triangles[triIndex + 4] = index + 1;
triangles[triIndex + 5] = index + resolution + 1;
triIndex += 6;
}
}
}
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
public class PlanetGenerator : MonoBehaviour
{
[Range(2, 256)]
public int Resolution = 10;
public PlanetSettings Settings;
[SerializeField, HideInInspector]
MeshFilter[] meshFilters;
TerrainFace[] terrainFaces;
Color c;
private void OnValidate()
{
GeneratePlanet();
}
void Initialize()
{
switch (Settings.type)
{
case Type.Desert:
c = new Color(244, 176, 66, 255);
break;
case Type.Forest:
c = new Color(9, 119, 22, 255);
break;
case Type.Grass:
c = new Color(21, 193, 41, 255);
break;
case Type.Ice:
c = new Color(105, 206, 239, 255);
break;
case Type.Rocky:
c = new Color(104, 65, 6, 255);
break;
case Type.Snow:
c = new Color(204, 226, 229, 255);
break;
case Type.Volcano:
c = new Color(160, 16, 16, 255);
break;
case Type.Water:
c = new Color(26, 69, 178, 255);
break;
default:
c = new Color();
break;
}
if (meshFilters == null || meshFilters.Length == 0)
meshFilters = new MeshFilter[6];
terrainFaces = new TerrainFace[6];
Vector3[] directions = { Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back };
for (int i = 0; i < 6; i++)
{
if (meshFilters[i] == null)
{
GameObject meshObj = new GameObject("mesh");
meshObj.transform.parent = transform;
meshObj.AddComponent<MeshRenderer>().sharedMaterial = new Material(Shader.Find("Standard"));
meshFilters[i] = meshObj.AddComponent<MeshFilter>();
meshFilters[i].sharedMesh = new Mesh();
}
terrainFaces[i] = new TerrainFace(meshFilters[i].sharedMesh, Resolution, directions[i], Settings);
}
}
public void GeneratePlanet()
{
Initialize();
GenerateMesh();
GenerateColor();
}
void GenerateMesh()
{
foreach (TerrainFace face in terrainFaces)
{
face.ConstructMesh();
}
}
void GenerateColor()
{
foreach (MeshFilter m in meshFilters)
{
m.GetComponent<MeshRenderer>().sharedMaterial.color = c;
}
}
}
The size part works, it's just the color that doesn't. I should see a dark red colored sphere. I have been trying different things to identify the problem, I think i have narrowed it down to sharedmaterial.color but I don't know for sure.
Well you don't have the code he talks about at around the 5 min mark where he changed the TerrainFace object and it's constructor.

Best way to speed up CropTransparentPixels method

I have just wrote this method to crop transparent pixels from images.
It seems to work ok but it is very slow because of GetPixel - any ideas on how to make the algorithm logic quicker?
I know I can change the GetPixel for faster (but unsafe) access code and I might do so, however I am after ways to avoid doing a full scan. I want advice on how to make the logic behind this algorithm quicker.
public Bitmap CropTransparentPixels(Bitmap originalBitmap)
{
// Find the min/max transparent pixels
Point min = new Point(int.MaxValue, int.MaxValue);
Point max = new Point(int.MinValue, int.MinValue);
for (int x = 0; x < originalBitmap.Width; ++x)
{
for (int y = 0; y < originalBitmap.Height; ++y)
{
Color pixelColor = originalBitmap.GetPixel(x, y);
if (pixelColor.A == 255)
{
if (x < min.X) min.X = x;
if (y < min.Y) min.Y = y;
if (x > max.X) max.X = x;
if (y > max.Y) max.Y = y;
}
}
}
// Create a new bitmap from the crop rectangle
Rectangle cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
Bitmap newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height);
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.DrawImage(originalBitmap, 0, 0, cropRectangle, GraphicsUnit.Pixel);
}
return newBitmap;
}
This is the method I ended up writing and it is much faster.
public static Bitmap CropTransparentPixels(this Bitmap bmp)
{
BitmapData bmData = null;
try
{
bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int scanline = bmData.Stride;
IntPtr Scan0 = bmData.Scan0;
Point top = new Point(), left = new Point(), right = new Point(), bottom = new Point();
bool complete = false;
unsafe
{
byte* p = (byte*)(void*)Scan0;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
if (p[3] != 0)
{
top = new Point(x, y);
complete = true;
break;
}
p += 4;
}
if (complete)
break;
}
p = (byte*)(void*)Scan0;
complete = false;
for (int y = bmp.Height - 1; y >= 0; y--)
{
for (int x = 0; x < bmp.Width; x++)
{
if (p[x * 4 + y * scanline + 3] != 0)
{
bottom = new Point(x + 1, y + 1);
complete = true;
break;
}
}
if (complete)
break;
}
p = (byte*)(void*)Scan0;
complete = false;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
if (p[x * 4 + y * scanline + 3] != 0)
{
left = new Point(x, y);
complete = true;
break;
}
}
if (complete)
break;
}
p = (byte*)(void*)Scan0;
complete = false;
for (int x = bmp.Width - 1; x >= 0; x--)
{
for (int y = 0; y < bmp.Height; y++)
{
if (p[x * 4 + y * scanline + 3] != 0)
{
right = new Point(x + 1, y + 1);
complete = true;
break;
}
}
if (complete)
break;
}
}
bmp.UnlockBits(bmData);
System.Drawing.Rectangle rectangle = new Rectangle(left.X, top.Y, right.X - left.X, bottom.Y - top.Y);
Bitmap b = new Bitmap(rectangle.Width, rectangle.Height);
Graphics g = Graphics.FromImage(b);
g.DrawImage(bmp, 0, 0, rectangle, GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch
{
try
{
bmp.UnlockBits(bmData);
}
catch { }
return null;
}
}

C# Zoom In and Zoom Out On A Image

I want to make a program have zoom in and zoom out function.(2x,4x,8x)But I can't use a available zoom function.I have to write a new one.I have done importing bitmap image.And I can get rgb color for each pixel.I created matrisses colorR,colorG and colorB for r,g and b colors.After that I thought I can create the 2x zoomed image with SolidBrush on a panel.I will draw 2x image like this:
Original Image (For example 3x3 pixels) (p=pixel color and "_" for space)
p1_p2_p3
p4_p5_p6
p7_p8_p9
2x Zoomed Image (6x6 pixels because of orginal image size) (p=pixel color of orginal image and "_" for space)
p1_p1_p2_p2_p3_p3
p1_p1_p2_p2_p3_p3
p4_p4_p5_p5_p6_p6
p4_p4_p5_p5_p6_p6
p7_p7_p8_p8_p9_p9
p7_p7_p8_p8_p9_p9
I wrote one loop but it didn't work because it is complety wrong.So how can I write for loops ?
private void button4_Click(object sender, EventArgs e) {
listBox1.Items.Clear();//insignificant
listBox2.Items.Clear();//insignificant
listBox3.Items.Clear();//insignificant
using (OpenFileDialog dlg = new OpenFileDialog()) {
dlg.Title = "Open Image";
dlg.Filter = "*.bmp|*.bmp|*.*|*.*";
if (dlg.ShowDialog() == DialogResult.OK) {
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
private void button1_Click(object sender, EventArgs e) {
Graphics my2xImage = panel1.CreateGraphics();
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
int[,] colorR = new int[bmpHeight, bmpWidth];
int[,] colorG = new int[bmpHeight, bmpWidth];
int[,] colorB = new int[bmpHeight, bmpWidth];
for (int y = 0; y < bmpHeight; y++) {
for (int x = 0; x < bmpWidth; x++) {
Color pixelColor = bmpFirst.GetPixel(x, y);
colorR[x, y] = pixelColor.R;
colorG[x, y] = pixelColor.G;
colorB[x, y] = pixelColor.B;
listBox1.Items.Add("(" + (x + 1) + "," + (y + 1) + ")" + " " + colorR[x, y]);//insignificant
listBox2.Items.Add("(" + (x + 1) + "," + (y + 1) + ")" + " " + colorG[x, y]);//insignificant
listBox3.Items.Add("(" + (x + 1) + "," + (y + 1) + ")" + " " + colorB[x, y]);//insignificant
}
}
//for (int y = 0; y < (bmpHeight * 2); y++)
//{
// for (int x = 0; x < (bmpWidth * 2); x++)
// {
// Color mySpecialColor = Color.FromArgb(colorR[x,y], colorG[x,y], colorB[x,y]);
// SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
// my2xImage.FillRectangle(pixelBrush, x, y, 1, 1);
// }
//}
}
private void button5_Click(object sender, EventArgs e) {
}
private void button2_Click(object sender, EventArgs e) {
}
This is insane, but if you really must do it this way, then try something like this:
int dx = x*2;
int dy = y*2;
colorR[dx ,dy ] = pixelColor.R;
colorR[dx+1,dy ] = pixelColor.R;
colorR[dx ,dy+1] = pixelColor.R;
colorR[dx+1,dy+1] = pixelColor.R;
colorG[dx ,dy ] = pixelColor.G;
colorG[dx+1,dy ] = pixelColor.G;
colorG[dx ,dy+1] = pixelColor.G;
colorG[dx+1,dy+1] = pixelColor.G;
colorB[dx ,dy ] = pixelColor.B;
colorB[dx+1,dy ] = pixelColor.B;
colorB[dx ,dy+1] = pixelColor.B;
colorB[dx+1,dy+1] = pixelColor.B;
You should use the DrawImage method of the Graphics class.
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = Graphics.FromImage(bmpFirst);
// Draw image to screen.
g.DrawImage(newImage, destRect, x, y, width, height, units);
Look here: https://msdn.microsoft.com/en-us/library/ms142045(v=vs.110).aspx
Look here also: https://msdn.microsoft.com/en-us/library/k0fsyd4e(v=vs.110).aspx
You can even set the interpolation mode: https://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.interpolationmode(v=vs.110).aspx
You are looking for the NearestNeighbor interpolation mode.
He is the solution.
private void button4_Click(object sender, EventArgs e )
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "*.bmp|*.bmp|*.*|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel1.CreateGraphics();
int[,] colorR = new int[bmpHeight*2 , bmpWidth*2];
int[,] colorG = new int[bmpHeight*2 , bmpWidth*2];
int[,] colorB = new int[bmpHeight*2 , bmpWidth*2];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
int dx = x * 2;
int dy = y * 2;
colorR[dx, dy] = pixelColor.R;
colorR[dx + 1, dy] = pixelColor.R;
colorR[dx, dy + 1] = pixelColor.R;
colorR[dx + 1, dy + 1] = pixelColor.R;
colorG[dx, dy] = pixelColor.G;
colorG[dx + 1, dy] = pixelColor.G;
colorG[dx, dy + 1] = pixelColor.G;
colorG[dx + 1, dy + 1] = pixelColor.G;
colorB[dx, dy] = pixelColor.B;
colorB[dx + 1, dy] = pixelColor.B;
colorB[dx, dy + 1] = pixelColor.B;
colorB[dx + 1, dy + 1] = pixelColor.B;
}
}
for (int y = 0; y < (bmpHeight*2); y++)
{
for (int x = 0; x < (bmpWidth*2); x++)
{
Color mySpecialColor = Color.FromArgb(colorR[x, y], colorG[x, y], colorB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
You can use for loops for color[dx,dy] parts.Here it is for 8x zoom.
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel3.CreateGraphics();
int[,] colorR = new int[bmpHeight * 8, bmpWidth * 8];
int[,] colorG = new int[bmpHeight * 8, bmpWidth * 8];
int[,] colorB = new int[bmpHeight * 8, bmpWidth * 8];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
int dx = x * 8;
int dy = y * 8;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
colorR[dx + j, dy + i] = pixelColor.R;
colorG[dx + j, dy + i] = pixelColor.G;
colorB[dx + j, dy + i] = pixelColor.B;
}
}
}
Full code (Also you can download project: Link
private void button4_Click(object sender, EventArgs e )
{
tabControl1.SelectedTab = tabPage1;
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "*.bmp|*.bmp|*.jpg|*.jpg|*.*|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
if (pictureBox1.Image == null)
{
MessageBox.Show("Please choose a image file.");
}
else
{
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
if (bmpHeight > 100 || bmpWidth > 100)
{
MessageBox.Show("Image size can't be bigger than 100x100 pixels");
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button10.Enabled = false;
}
else
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button10.Enabled = false;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage2;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel1.CreateGraphics();
int[,] colorR = new int[bmpWidth * 2 , bmpHeight *2];
int[,] colorG = new int[bmpWidth * 2 , bmpHeight *2];
int[,] colorB = new int[bmpWidth * 2 , bmpHeight *2];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
int dx = x * 2;
int dy = y * 2;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
colorR[dx + i, dy + j] = pixelColor.R;
colorG[dx + i, dy + j] = pixelColor.G;
colorB[dx + i, dy + j] = pixelColor.B;
}
}
}
}
for (int y = 0; y < (bmpHeight*2); y++)
{
for (int x = 0; x < (bmpWidth*2); x++)
{
Color mySpecialColor = Color.FromArgb(colorR[x, y], colorG[x, y], colorB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage3;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel2.CreateGraphics();
int[,] colorR = new int[bmpWidth * 4, bmpHeight * 4];
int[,] colorG = new int[bmpWidth * 4, bmpHeight * 4];
int[,] colorB = new int[bmpWidth * 4, bmpHeight * 4];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
int dx = x * 4;
int dy = y * 4;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
colorR[dx + i, dy + j] = pixelColor.R;
colorG[dx + i, dy + j] = pixelColor.G;
colorB[dx + i, dy + j] = pixelColor.B;
}
}
}
}
for (int y = 0; y < (bmpHeight * 4); y++)
{
for (int x = 0; x < (bmpWidth * 4); x++)
{
Color mySpecialColor = Color.FromArgb(colorR[x, y], colorG[x, y], colorB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button5_Click_1(object sender, EventArgs e)
{
}
private void tabPage2_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage4;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel3.CreateGraphics();
int[,] colorR = new int[bmpWidth * 8, bmpHeight * 8];
int[,] colorG = new int[bmpWidth * 8, bmpHeight * 8];
int[,] colorB = new int[bmpWidth * 8, bmpHeight * 8];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
int dx = x * 8;
int dy = y * 8;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
colorR[dx + i, dy + j] = pixelColor.R;
colorG[dx + i, dy + j] = pixelColor.G;
colorB[dx + i, dy + j] = pixelColor.B;
}
}
}
}
for (int y = 0; y < (bmpHeight * 8); y++)
{
for (int x = 0; x < (bmpWidth * 8); x++)
{
Color mySpecialColor = Color.FromArgb(colorR[x, y], colorG[x, y], colorB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void button5_Click_2(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage5;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel4.CreateGraphics();
int[,] colorR = new int[bmpWidth, bmpHeight];
int[,] colorG = new int[bmpWidth, bmpHeight];
int[,] colorB = new int[bmpWidth, bmpHeight];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
colorR[x, y] = pixelColor.R;
colorG[x, y] = pixelColor.G;
colorB[x, y] = pixelColor.B;
}
}
int[,] colorSR = new int[bmpWidth /2, bmpHeight /2];
int[,] colorSG = new int[bmpWidth /2, bmpHeight /2];
int[,] colorSB = new int[bmpWidth /2, bmpHeight /2];
for (int i = 0; i < bmpWidth / 2; i++)
{
for (int j = 0; j < bmpHeight /2; j++)
{
colorSR[i, j] = (colorR[2 * i, 2 * j] + colorR[2 * i, 2 * j + 1] + colorR[2 * i + 1, 2 * j] + colorR[2 * i + 1, 2 * j + 1]) / 4;
colorSG[i, j] = (colorG[2 * i, 2 * j] + colorG[2 * i, 2 * j + 1] + colorG[2 * i + 1, 2 * j] + colorG[2 * i + 1, 2 * j + 1]) / 4;
colorSB[i, j] = (colorB[2 * i, 2 * j] + colorB[2 * i, 2 * j + 1] + colorB[2 * i + 1, 2 * j] + colorB[2 * i + 1, 2 * j + 1]) / 4;
}
}
for (int y = 0; y < (bmpHeight / 2); y++)
{
for (int x = 0; x < (bmpWidth / 2); x++)
{
Color mySpecialColor = Color.FromArgb(colorSR[x, y], colorSG[x, y], colorSB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button6_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage6;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel5.CreateGraphics();
int[,] colorR = new int[bmpWidth, bmpHeight];
int[,] colorG = new int[bmpWidth, bmpHeight];
int[,] colorB = new int[bmpWidth, bmpHeight];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
colorR[x, y] = pixelColor.R;
colorG[x, y] = pixelColor.G;
colorB[x, y] = pixelColor.B;
}
}
int[,] colorSR = new int[bmpWidth / 4, bmpHeight / 4];
int[,] colorSG = new int[bmpWidth / 4, bmpHeight / 4];
int[,] colorSB = new int[bmpWidth / 4, bmpHeight / 4];
for (int i = 0; i < bmpWidth / 4; i++)
{
for (int j = 0; j < bmpHeight / 4; j++)
{
colorSR[i, j] = (colorR[4 * i, 4 * j] + colorR[4 * i, 4 * j + 1] + colorR[4 * i + 1, 4 * j] + colorR[4 * i + 1, 4 * j + 1]) / 4;
colorSG[i, j] = (colorG[4 * i, 4 * j] + colorG[4 * i, 4 * j + 1] + colorG[4 * i + 1, 4 * j] + colorG[4 * i + 1, 4 * j + 1]) / 4;
colorSB[i, j] = (colorB[4 * i, 4 * j] + colorB[4 * i, 4 * j + 1] + colorB[4 * i + 1, 4 * j] + colorB[4 * i + 1, 4 * j + 1]) / 4;
}
}
for (int y = 0; y < (bmpHeight / 4); y++)
{
for (int x = 0; x < (bmpWidth / 4); x++)
{
Color mySpecialColor = Color.FromArgb(colorSR[x, y], colorSG[x, y], colorSB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void button7_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage7;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel6.CreateGraphics();
int[,] colorR = new int[bmpWidth, bmpHeight];
int[,] colorG = new int[bmpWidth, bmpHeight];
int[,] colorB = new int[bmpWidth, bmpHeight];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
colorR[x, y] = pixelColor.R;
colorG[x, y] = pixelColor.G;
colorB[x, y] = pixelColor.B;
}
}
int[,] colorSR = new int[bmpWidth / 8, bmpHeight / 8];
int[,] colorSG = new int[bmpWidth / 8, bmpHeight / 8];
int[,] colorSB = new int[bmpWidth / 8, bmpHeight / 8];
for (int i = 0; i < bmpWidth / 8; i++)
{
for (int j = 0; j < bmpHeight / 8; j++)
{
colorSR[i, j] = (colorR[8 * i, 8 * j] + colorR[8 * i, 8 * j + 1] + colorR[8 * i + 1, 8 * j] + colorR[8 * i + 1, 8 * j + 1]) / 4;
colorSG[i, j] = (colorG[8 * i, 8 * j] + colorG[8 * i, 8 * j + 1] + colorG[8 * i + 1, 8 * j] + colorG[8 * i + 1, 8 * j + 1]) / 4;
colorSB[i, j] = (colorB[8 * i, 8 * j] + colorB[8 * i, 8 * j + 1] + colorB[8 * i + 1, 8 * j] + colorB[8 * i + 1, 8 * j + 1]) / 4;
}
}
for (int y = 0; y < (bmpHeight / 8); y++)
{
for (int x = 0; x < (bmpWidth / 8); x++)
{
Color mySpecialColor = Color.FromArgb(colorSR[x, y], colorSG[x, y], colorSB[x, y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void button8_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "*.bmp|*.bmp|*.jpg|*.jpg|*.*|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
if (pictureBox1.Image == null)
{
MessageBox.Show("Please choose a image file.");
}
else
{
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
if (bmpHeight > 800 || bmpWidth > 800)
{
MessageBox.Show("Image size can't be bigger than 800x800 pixels.");
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button10.Enabled = false;
}
else
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button10.Enabled = false;
}
}
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
tabControl1.SelectedTab = tabPage8;
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
Bitmap bmpFirst = (Bitmap)pictureBox1.Image.Clone();
Graphics g = panel7.CreateGraphics();
int[,] colorR = new int[bmpWidth, bmpHeight];
int[,] colorG = new int[bmpWidth, bmpHeight];
int[,] colorB = new int[bmpWidth, bmpHeight];
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
Color pixelColor = bmpFirst.GetPixel(x, y);
colorR[x, y] = pixelColor.R;
colorG[x, y] = pixelColor.G;
colorB[x, y] = pixelColor.B;
}
}
for (int y = 0; y < bmpHeight; y++)
{
for (int x = 0; x < bmpWidth; x++)
{
int dx = bmpWidth - 1;
int dy = bmpHeight - 1;
Color mySpecialColor = Color.FromArgb(colorR[dx - x, dy - y], colorG[dx - x, dy - y], colorB[dx - x, dy - y]);
SolidBrush pixelBrush = new SolidBrush(mySpecialColor);
g.FillRectangle(pixelBrush, x, y, 1, 1);
}
}
}
private void button9_Click(object sender, EventArgs e)
{
tabControl1.SelectedTab = tabPage1;
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "*.bmp|*.bmp|*.jpg|*.jpg|*.*|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
if (pictureBox1.Image == null)
{
MessageBox.Show("Please choose a image file.");
}
else
{
int bmpHeight = pictureBox1.Image.Height;
int bmpWidth = pictureBox1.Image.Width;
if (bmpHeight > 800 || bmpWidth > 800)
{
MessageBox.Show("Image size can't be bigger than 800x800 pixels");
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button10.Enabled = false;
}
else
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button10.Enabled = true;
}
}
}
}

Save data to a file when a button is clicked? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm making an application for a ledcube in C#.
All it does now is allow the user to click on some buttons to change the color of the desired led's.
I'm trying to imply a function which allows the user to save the current configuration (of colors) to a file, which later can be read by a programming bord.
The saved file must contain binary code for each led (whether the led is on, and which color: off, red, green, orange).
I was thinking that 1 led can contain a value between 00 - 11 (so 0 and 3).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] laag_1 = new Button[8, 8];
Button[,] laag_2 = new Button[8, 8];
Button[,] laag_3 = new Button[8, 8];
Button[,] laag_4 = new Button[8, 8];
Button[,] laag_5 = new Button[8, 8];
Button[,] laag_6 = new Button[8, 8];
Button[,] laag_7 = new Button[8, 8];
Button[,] laag_8 = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_1[x, y] = new Button();
laag_1[x, y].SetBounds((50 * x) + 100, (50 * y) + 30, 40, 40);
laag_1[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_1[x, y]);
laag_1[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_2.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_2[x, y] = new Button();
laag_2[x, y].SetBounds((50 * x) + 520, (50 * y) + 30, 40, 40);
laag_2[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_2[x, y]);
laag_2[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_3.GetLength(0); x++)
{
for (int y = 0; y < laag_3.GetLength(1); y++)
{
laag_3[x, y] = new Button();
laag_3[x, y].SetBounds((50 * x) + 940, (50 * y) + 30, 40, 40);
laag_3[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_3[x, y]);
laag_3[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_4.GetLength(0); x++)
{
for (int y = 0; y < laag_4.GetLength(1); y++)
{
laag_4[x, y] = new Button();
laag_4[x, y].SetBounds((50 * x) + 1360, (50 * y) + 30, 40, 40);
laag_4[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_4[x, y]);
laag_4[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_5.GetLength(0); x++)
{
for (int y = 0; y < laag_5.GetLength(1); y++)
{
laag_5[x, y] = new Button();
laag_5[x, y].SetBounds((50 * x) + 100, (50 * y) + 520, 40, 40);
laag_5[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_5[x, y]);
laag_5[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_6.GetLength(0); x++)
{
for (int y = 0; y < laag_6.GetLength(1); y++)
{
laag_6[x, y] = new Button();
laag_6[x, y].SetBounds((50 * x) + 520, (50 * y) + 520, 40, 40);
laag_6[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_6[x, y]);
laag_6[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_7.GetLength(0); x++)
{
for (int y = 0; y < laag_7.GetLength(1); y++)
{
laag_7[x, y] = new Button();
laag_7[x, y].SetBounds((50 * x) + 940, (50 * y) + 520, 40, 40);
laag_7[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_7[x, y]);
laag_7[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_8.GetLength(0); x++)
{
for (int y = 0; y < laag_8.GetLength(1); y++)
{
laag_8[x, y] = new Button();
laag_8[x, y].SetBounds((50 * x) + 1360, (50 * y) + 520, 40, 40);
laag_8[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_8[x, y]);
laag_8[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"C:\testmap\laag_1.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != laag_1.GetLength(0) * laag_1.GetLength(1) * 2)
return;
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
int position = (y * laag_1.GetLength(0) + x);
string value = ((char)data[2 * position]).ToString() + ((char)data[2 * position + 1]).ToString();
Color color;
switch (value)
{
case "01":
color = Color.Red;
break;
case "00":
color = Color.Black;
break;
case "10":
color = Color.Green;
break;
case "11":
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
laag_1[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
Dictionary<Form1, int> d = new Dictionary<Form1, int>();
byte[] data = new byte[laag_1.GetLength(0) * laag_1.GetLength(1) * 2];
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
int position = (y * laag_1.GetLength(0) + x);
string value;
switch (laag_1[x, y].BackColor.Name)
{
case "Red":
value = "01";
break;
case "Black":
value = "00";
break;
case "Green":
value = "10";
break;
case "Yellow":
value = "11";
break;
default:
value = "00";
break;
}
data[2 * position] = (byte)value[0];
data[2 * position + 1] = (byte)value[1];
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_1[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_2.GetLength(0); x++)
{
for (int y = 0; y < laag_2.GetLength(1); y++)
{
laag_2[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_3.GetLength(0); x++)
{
for (int y = 0; y < laag_3.GetLength(1); y++)
{
laag_3[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_4.GetLength(0); x++)
{
for (int y = 0; y < laag_4.GetLength(1); y++)
{
laag_4[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_5.GetLength(0); x++)
{
for (int y = 0; y < laag_5.GetLength(1); y++)
{
laag_5[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_6.GetLength(0); x++)
{
for (int y = 0; y < laag_6.GetLength(1); y++)
{
laag_6[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_7.GetLength(0); x++)
{
for (int y = 0; y < laag_7.GetLength(1); y++)
{
laag_7[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_8.GetLength(0); x++)
{
for (int y = 0; y < laag_8.GetLength(1); y++)
{
laag_8[x, y].BackColor = Color.Black;
}
}
}
}
}
You could take a look at the File.WriteAllBytes and File.ReadAllBytes methods for saving and loading of the file.
Also take a look at the OpenFileDialog control for choosing what file to open.
Further, there's no need to be stingy with values, you can (and should) use a full byte for every button, just loop the buttons and insert the values in a byte[], and then write them out to a file.
I assume You want to use Object Serialization for this.
XMLSerialization: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization
BinarySerialization: http://msdn.microsoft.com/en-us/library/72hyey7b(v=vs.71).aspx
If you want to save data and then read it by another application I am suggesting you a Serialization, because You don't have to worry about reading from file.
Try this:
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
byte[] data = System.IO.File.ReadAllBytes(filePath);
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
int index = position / 8;
int shift = position % 8;
byte value = (byte)((data[index] >> shift) % 4);
Color color;
switch (value)
{
case 1:
color = Color.Red;
break;
case 0:
color = Color.Black;
break;
case 2:
color = Color.Green;
break;
case 3:
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[(7 + btn.GetLength(0) * btn.GetLength(1) * 2) / 8];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
byte value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = 1;
break;
case "Black":
value = 0;
break;
case "Green":
value = 2;
break;
case "Yellow":
value = 3;
break;
default:
value = 0;
break;
}
int index = position / 8;
int shift = position % 8;
data[index] = (byte)(data[index] | (value << shift));
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
[Updated]:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
if (System.IO.File.Exists(filePath))
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
byte[] data = System.IO.File.ReadAllBytes(filePath);
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
int index = position / 8;
int shift = position % 8;
byte value = (byte)((data[index] >> shift) % 4);
Color color;
switch (value)
{
case 1:
color = Color.Red;
break;
case 0:
color = Color.Black;
break;
case 2:
color = Color.Green;
break;
case 3:
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[(7 + btn.GetLength(0) * btn.GetLength(1) * 2) / 8];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
byte value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = 1;
break;
case "Black":
value = 0;
break;
case "Green":
value = 2;
break;
case "Yellow":
value = 3;
break;
default:
value = 0;
break;
}
int index = position / 8;
int shift = position % 8;
data[index] = (byte)(data[index] | (value << shift));
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}
[Update #2] Reworking storage as full byte for each led:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != btn.GetLength(0) * btn.GetLength(1))
return;
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
char value = (char)data[position];
Color color;
switch (value)
{
case '1':
color = Color.Red;
break;
case '0':
color = Color.Black;
break;
case '2':
color = Color.Green;
break;
case '3':
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[btn.GetLength(0) * btn.GetLength(1)];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
char value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = '1';
break;
case "Black":
value = '0';
break;
case "Green":
value = '2';
break;
case "Yellow":
value = '3';
break;
default:
value = '0';
break;
}
data[position] = (byte)value;
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}
Update #3:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != btn.GetLength(0) * btn.GetLength(1) * 2)
return;
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value = ((char)data[2 * position]).ToString() + ((char)data[2 * position + 1]).ToString();
Color color;
switch (value)
{
case "01":
color = Color.Red;
break;
case "00":
color = Color.Black;
break;
case "10":
color = Color.Green;
break;
case "11":
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
Dictionary<Form1, int> d = new Dictionary<Form1, int>();
byte[] data = new byte[btn.GetLength(0) * btn.GetLength(1) * 2];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = "01";
break;
case "Black":
value = "00";
break;
case "Green":
value = "10";
break;
case "Yellow":
value = "11";
break;
default:
value = "00";
break;
}
data[2 * position] = (byte)value[0];
data[2 * position + 1] = (byte)value[1];
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}

Categories

Resources