unity array having 50 gameobjects but displays only 10 object - arrays

i have build a level menu with levels, i also created and empty array (GameObject[ ] lvlBut; )to store the level icons instantiated, but only 10 level icons are displayed on the screen where as i have 50 levels. for some reason its only taking 10 levels and i don’t t know where i have gone wrong. any suggestions?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI;
using TMPro;
public class LevelSelector : MonoBehaviour{
public GameObject levelHolder;
public GameObject levelIcon;
public GameObject thisCanvas;
public int numberOfLevels = 50;
public Vector2 iconSpacing;
private Rect panelDimensions;
private Rect iconDimensions;
private int amountPerPage;
private int currentLevelCount;
int levelsUnlocked;
GameObject[] lvlBut;
void Start()
{
panelDimensions = levelHolder.GetComponent<RectTransform>().rect;
iconDimensions = levelIcon.GetComponent<RectTransform>().rect;
int maxInARow = Mathf.FloorToInt((panelDimensions.width + iconSpacing.x) / (iconDimensions.width + iconSpacing.x));
int maxInACol = Mathf.FloorToInt((panelDimensions.height + iconSpacing.y) / (iconDimensions.height + iconSpacing.y));
amountPerPage = maxInARow * maxInACol;
int totalPages = Mathf.CeilToInt((float)numberOfLevels / amountPerPage);
LoadPanels(totalPages);
}
void LoadPanels(int numberOfPanels)
{
GameObject panelClone = Instantiate(levelHolder) as GameObject;
PageSwiper swiper = levelHolder.AddComponent<PageSwiper>();
swiper.totalPages = numberOfPanels;
for (int i = 1; i <= numberOfPanels; i++)
{
GameObject panel = Instantiate(panelClone) as GameObject;
panel.transform.SetParent(thisCanvas.transform, false);
panel.transform.SetParent(levelHolder.transform);
panel.name = "Page-" + i;
panel.GetComponent<RectTransform>().localPosition = new Vector2(panelDimensions.width * (i - 1), 0);
SetUpGrid(panel);
int numberOfIcons = i == numberOfPanels ? numberOfLevels - currentLevelCount : amountPerPage;
LoadIcons(numberOfIcons, panel);
}
Destroy(panelClone);
}
void SetUpGrid(GameObject panel)
{
GridLayoutGroup grid = panel.AddComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(iconDimensions.width, iconDimensions.height);
grid.childAlignment = TextAnchor.MiddleCenter;
grid.spacing = iconSpacing;
}
void LoadIcons(int numberOfIcons, GameObject parentObject)
{
for (int i = 1; i <= numberOfIcons; i++)
{
currentLevelCount++;
GameObject icon = Instantiate(levelIcon) as GameObject;
icon.transform.SetParent(thisCanvas.transform, false);
icon.transform.SetParent(parentObject.transform);
icon.name = "Level " + i;
icon.GetComponentInChildren<TextMeshProUGUI>().SetText(currentLevelCount.ToString());
}
lvlBut = GameObject.FindGameObjectsWithTag("LevelButton");
levelsUnlocked = PlayerPrefs.GetInt("levelsUnlocked", 1);
for (int i = 0; i < lvlBut.Length; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = false;
}
for (int i = 0; i < levelsUnlocked; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = true;
}
}
}

Related

How can I save 3-dimension array into file and load later

I'm trying to save the 3D array witch has position data of the blocks with Unity and I can't find out how to save it.
public class Block
{
public Vector3 position;
public short blockType;
public byte facing;
public Block(Vector3 pos, short t, byte f)
{
position = pos;
blockType = t;
facing = f;
}
}
This is the block class which I stored the information about block.
public Block[,,] WorldBlock = new Block[100, 10, 100];
This is the array I want to save and it has 100000 blocks in it.
There are many ways how to approach this.
One way would e.g. be Newtonsoft JSON (comes as a package via the PackageManager and even pre-installed in latest Unity versions)
using Newtonsoft.Json;
....
public Block[,,] WorldBlock = new Block[100, 10, 100];
private string filePath => Path.Combine(Application.persistentDataPath, "example.json");
private void Save()
{
var json = JsonConvert.SerializeObject(WorldBlock);
File.WriteAllText(filePath, json);
}
private void Load()
{
if (File.Exists(filePath))
{
var json = File.ReadAllText(filePath);
WorldBlock = JsonConvert.DeserializeObject<Block[,,]>(json);
}
var block = WorldBlock[1, 2, 3];
Debug.Log($"{block.position} - {block.blockType} - {block.facing}");
}
Or - since JSON wastes a lot of character space for your use case - you could also implement you own binary serialization e.g. usingBinaryReader and BinaryWriter
in something like e.g.
[Serializable]
public class Block
{
public Vector3 position;
public short blockType;
public byte facing;
public Block(Vector3 pos, short t, byte f)
{
position = pos;
blockType = t;
facing = f;
}
public void Serialize(BinaryWriter writer)
{
writer.Write(position.x);
writer.Write(position.y);
writer.Write(position.z);
writer.Write(blockType);
writer.Write(facing);
}
public void Deserialize(BinaryReader reader)
{
position. x = reader.ReadSingle();
position. y = reader.ReadSingle();
position. z = reader.ReadSingle();
blockType = reader.ReadInt16();
facing = reader.ReadByte();
}
}
and then do
private void Save()
{
using (var stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var writer = new BinaryWriter(stream))
{
// first store the size of each dimension
for (var i = 0; i < WorldBlock.Rank; i++)
{
writer.Write(WorldBlock.GetLength(i));
}
// then serialize all blocks
for (var i = 0; i < WorldBlock.GetLength(0); i++)
{
for (var j = 0; j < WorldBlock.GetLength(1); j++)
{
for (var k = 0; k < WorldBlock.GetLength(2); k++)
{
var block = WorldBlock[i, j, k];
block.Serialize(writer);
}
}
}
}
}
}
private void Load()
{
if (File.Exists(filePath))
{
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
// first get th size of each dimension
var x = reader.ReadInt32();
var y = reader.ReadInt32();
var z = reader.ReadInt32();
WorldBlock = new Block[x, y, z];
// then deserialize all blocks
for (var i = 0; i < WorldBlock.GetLength(0); i++)
{
for (var j = 0; j < WorldBlock.GetLength(1); j++)
{
for (var k = 0; k < WorldBlock.GetLength(2); k++)
{
var block = new Block();
block.Deserialize(reader);
WorldBlock[i, j, k] = block;
}
}
}
}
}
}
var exampleBlock = WorldBlock[1, 2, 3];
Debug.Log($"{exampleBlock.position} - {exampleBlock.blockType} - {exampleBlock.facing}");
}

How to let Stage show the pictures after timer

After I click start button, my program will not show the second scene and thread , until the thread is finish. And the thread will not run correctly(grass didn't increase).
public class test111 extends Application {
private static int grass_i=130;
private static int grass_j=200;
private static int[][] map = new int[grass_i][grass_j];//草地資料grassdata
private static int totalgrass; //grass total number
private static int totalgrassrest; //grass rest number
private static int months=1; //月
private Timer timer;//時間
//GUI
Scene menusc ;
//START後的視窗
BorderPane bpAll = new BorderPane();
Pane playView = new Pane();
Scene mainsc = new Scene(bpAll);
//草
Image littlegrassImg = new Image(getClass().getResourceAsStream("map_littlegrass.png"));
Image midiumgrassImg = new Image(getClass().getResourceAsStream("map_midiumgrass.png"));
Image muchgrassImg = new Image(getClass().getResourceAsStream("map_muchgrass.png"));
Rectangle2D[][] viewportRect = new Rectangle2D[130][200];
private static ImageView[][] mapView = new ImageView[130][200];
//時間
#Override
public void start(Stage primaryStage) throws InterruptedException {
//MENU
Pane menu = new Pane();
menusc = new Scene(menu);
menu.setPrefSize(1000, 800);
Image MenuImg = new Image(getClass().getResourceAsStream("Menu_title.jpg"));
Image StartImg = new Image(getClass().getResourceAsStream("Start.jpg"));
menu.getChildren().add(new ImageView(MenuImg));
Button StartBt = new Button();
StartBt.setPrefSize(450, 150);
StartBt.setGraphic(new ImageView(StartImg));
StartBt.setMaxSize(450, 150);
StartBt.setLayoutX(300);
StartBt.setLayoutY(600);
menu.getChildren().addAll(new ImageView(MenuImg),StartBt);
primaryStage.setMinHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMinWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setMaxHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMaxWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setScene(menusc);
primaryStage.setTitle("Hypnos' yard");
//START
StartBt.setOnAction(e->{
BorderPane bp2 = bp2();
menusc = new Scene(bp2);
primaryStage.setScene(menusc);
});
primaryStage.show();
}
public BorderPane bp2(){
playView = playView();
bpAll = new BorderPane();
bpAll.setPrefSize(1000, 800);
playView.setPrefSize(1000, 650); //庭院
bpAll.setTop(playView);
Random ran = new Random();
totalgrass = (ran.nextInt(50)*1000)+48000;
totalgrassrest = totalgrass;
grasscreate();
//設定初始草地construct the initial grass
grassGraphicsLoading(); //loading grass pictures
return bpAll;
}
public Pane playView(){
playView = new Pane();
while(months<12){
timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
month();
}
};//after program executing 0.2s, a month past
timer.schedule(task, 200);
try {
Thread.sleep(200);
}
catch(InterruptedException e6) {
}
timer.cancel();
}
return playView;
}
//月month
protected void month(){
if(months<13){
grassgrow(totalgrass*2);//grass growth
Platform.runLater(new Runnable(){
#Override
public void run(){
grassGraphicsLoading();
}
});
months++;
}
}
//把草地資料帶入圖形loading grass pictures
private void grassGraphicsLoading(){
for (int i = 0; i < grass_i; i++) { // 設定imageView的圖形和位置
for (int j = 0; j < grass_j; j++) {
viewportRect[i][j] = new Rectangle2D(j * 5, i * 5, 5, 5);
if (170 <= j && j <= grass_j - 1) {
mapView[i][j] = new ImageView(muchgrassImg);
} else if (140 <= j && j < 170) {
mapView[i][j] = new ImageView(muchgrassImg);
} else {
if (map[i][j] == 0) {
mapView[i][j] = new ImageView(littlegrassImg);
} else if (map[i][j] == 1 || map[i][j] == 2) {
mapView[i][j] = new ImageView(midiumgrassImg);
} else {
mapView[i][j] = new ImageView(muchgrassImg);
}
}
playView.getChildren().add(mapView[i][j]);
mapView[i][j].setViewport(viewportRect[i][j]);
mapView[i][j].setX(j * 5);
mapView[i][j].setY(i * 5);
}
}
}
public static void main(String[] args) {
launch(args);
}
// 每經過30天(一個月)草地+1grassgrowth
protected void grassgrow(int sum) {
for (int i = 0; i < grass_i; i++) {
for (int j = grass_j - 1; j >= 0; j--) {
if (map[i][j] < 4 && totalgrass <sum) {
map[i][j] += 1;
totalgrass++;
}
if (totalgrass == 104000||totalgrass ==sum) {
break;
}
}
}
}
//建構草地construct grass
protected void grasscreate() {
for (int j = grass_j - 1; j >= 0; j--) {
for (int i = grass_i - 1; i >= 0; i--) {
if (170 <= j && j <= grass_j - 1) {
map[i][j] = 0;
} else if (140 <= j && j < 170) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest <= 0) {
map[i][j] = 0;
} else if (4 * (j + 1) * grass_i <= totalgrassrest) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest < 4) {
map[i][j] = totalgrassrest;
totalgrassrest = 0;
} else {
map[i][j] = rancreate();
totalgrassrest -= map[i][j];
}
}
}
totalgrass -= totalgrassrest;
totalgrassrest = 0;
}
// 一格(5X5)內草地數量隨機1-4平米z there is 1-4 grass inside a rectangle
private int rancreate() {
Random ran = new Random();
int grass = ran.nextInt(5);
return grass;
}
}`

WPF: Create XpsDocument Pagination

I am trying to create a Paginator that will in turn create an XpsDocument that I can preview with the and then print. I have the following code that I found on the web but do not understand how it is working.
The issue I am having is that if I run this as is, the pages are generated successfully. If I comment out the lines within OnRender() that generate the actual values of data (all the lines after Random...) I get pages that are about one row high and no text on them but they appear to be the correct length. What is it that is keeping the values of "Row Number" & "Column i" from being shown?
I have included 2 screen shots to illustrate.
public class TaxCodePrintPaginator : DocumentPaginator
{
private int _RowsPerPage;
private Size _PageSize;
private int _Rows;
private List<TaxCode> _dataList;
public TaxCodePrintPaginator(List<TaxCode> dt, int rows, Size pageSize)
{
_dataList = dt;
_Rows = rows;
PageSize = pageSize;
}
public override DocumentPage GetPage(int pageNumber)
{
int currentRow = _RowsPerPage * pageNumber;
var page = new PageElement(currentRow, Math.Min(_RowsPerPage, _Rows - currentRow))
{
Width = PageSize.Width,
Height = PageSize.Height
};
page.Arrange(new Rect(new Point(0, 0), PageSize));
return new DocumentPage(page);
}
public override bool IsPageCountValid
{ get { return true; } }
public override int PageCount
{ get { return (int)Math.Ceiling(_Rows / (double)_RowsPerPage); } }
public override Size PageSize
{
get { return _PageSize; }
set
{
_PageSize = value;
_RowsPerPage = 40;
//Can't print anything if you can't fit a row on a page
Debug.Assert(_RowsPerPage > 0);
}
}
public override IDocumentPaginatorSource Source
{ get { return null; } }
}
public class PageElement : UserControl
{
private const int PageMargin = 75;
private const int HeaderHeight = 25;
private const int LineHeight = 20;
private const int ColumnWidth = 140;
private int _CurrentRow;
private int _Rows;
public PageElement(int currentRow, int rows)
{
Margin = new Thickness(PageMargin);
_CurrentRow = currentRow;
_Rows = rows;
}
private static FormattedText MakeText(string text)
{
return new FormattedText(text, CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Tahoma"), 14, Brushes.Black);
}
public static int RowsPerPage(double height)
{
return (int)Math.Floor((height - (2 * PageMargin)
- HeaderHeight) / LineHeight);
}
protected override void OnRender(DrawingContext dc)
{
Point curPoint = new Point(0, 0);
dc.DrawText(MakeText("Row Number"), curPoint);
curPoint.X += ColumnWidth;
for (int i = 1; i < 4; i++)
{
dc.DrawText(MakeText("Column " + i), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.X = 0;
curPoint.Y += LineHeight;
dc.DrawRectangle(Brushes.Black, null, new Rect(curPoint, new Size(Width, 2)));
curPoint.Y += HeaderHeight - LineHeight;
Random numberGen = new Random();
for (int i = _CurrentRow; i < _CurrentRow + _Rows; i++)
{
dc.DrawText(MakeText(i.ToString()), curPoint);
curPoint.X += ColumnWidth;
for (int j = 1; j < 4; j++)
{
dc.DrawText(MakeText(numberGen.Next().ToString()), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.Y += LineHeight;
curPoint.X = 0;
}
}
}
Before
After

how to get the visible area of canvas in wpf

I am creating an application just like a paint in WPF, and I want to add zoom functionality to it. I am taking canvas as a parent and writable bitmap on it as child on which I draw. When the size of the canvas is small, I am drawing on writable bitmap smoothly, but when the size of the canvas is large, and zoom it, canvas size will be large, problem occur to draw on this large area. So I want to find the visible region of the canvas so that I can draw on it smoothly.
Please give me a source code to find the visible region of the canvas.
I have create this application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
namespace MapDesigner.Controls
{
class MapCanvas : Canvas
{
#region Routed Events
public static readonly RoutedEvent SelectedColorChangeEvent = EventManager.RegisterRoutedEvent(
"SelectedColorChange", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ucToolBox));
public event RoutedEventHandler SelectedColorChange
{
add { AddHandler(SelectedColorChangeEvent, value); }
remove { RemoveHandler(SelectedColorChangeEvent, value); }
}
#endregion
#region Enums
public enum Tool
{
Pencil,
FloodFill,
Eraser,
RectSelect,
Brush,
Part
}
#endregion
WriteableBitmap _wBMP;
Image _dispImg = new Image();
ScaleTransform st = new ScaleTransform();
int canvasHeight, canvasWidth;
double zoomLevel = 1;
Border brdGrid = new Border();
Color cellColor = Colors.Black;
Tool currentTool = Tool.Pencil;
int[,] array;
bool drawing = false;
bool showGrids = true;
public TextBlock tbPos;
public Tool CurrentTool
{
get
{
return currentTool;
}
set
{
currentTool = value;
}
}
public Color CellColor
{
get
{
return cellColor;
}
set
{
cellColor = value;
}
}
public bool GridsVisible
{
get
{
return showGrids;
}
set
{
showGrids = value;
}
}
public MapCanvas()
{
this.Children.Clear();
this.Children.Add(_dispImg);
//st.ScaleX = 1;
//st.ScaleY = 1;
// this.LayoutTransform = st;
}
void Refresh()
{
//canvas = new MapCanvas();
this.Children.Clear();
this.Children.Add(_dispImg);
st.ScaleX = 1;
st.ScaleY = 1;
this.Height = 0;
this.Width = 0;
zoomLevel = 1;
drawing = false;
}
public void LoadBMP(Uri bmpUri)
{
Refresh();
BitmapImage bmi = new BitmapImage(bmpUri);
_wBMP = new WriteableBitmap(bmi);
_dispImg.Source = _wBMP;
this.Height = bmi.Height;
this.Width = bmi.Width;
ShowGrids();
}
public void CreateBMP(int width, int height)
{
Refresh();
_wBMP = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr32, BitmapPalettes.WebPalette);
_wBMP.setPixel(Colors.White);
_dispImg.Source = _wBMP;
this.Height = height;
this.Width = width;
ShowGrids();
}
public void CreateNewDesign(Size mapSize)
{
Refresh();
_wBMP = new WriteableBitmap((int)mapSize.Width, (int)mapSize.Width, 96, 96, PixelFormats.Bgr32, BitmapPalettes.WebPalette);
_wBMP.setPixel(Colors.White);
_dispImg.Source = _wBMP;
array = new int[(_wBMP.PixelHeight + 1), (_wBMP.PixelWidth + 1)];
canvasWidth = (int)mapSize.Width;
canvasHeight = (int)mapSize.Height;
this.Height = mapSize.Height;
this.Width = mapSize.Width;
ShowGrids();
}
void ShowGrids()
{
return;
double width = 1;// _tileWidth + _tileMargin;
double height = 1;// _tileHeight + _tileMargin;
double numTileToAccumulate = 16;
Polyline gridCell = new Polyline();
gridCell.Margin = new Thickness(.5);
gridCell.Stroke = Brushes.LightBlue;
gridCell.StrokeThickness = 0.1;
gridCell.Points = new PointCollection(new Point[] { new Point(0, height-0.1),
new Point(width-0.1, height-0.1), new Point(width-0.1, 0) });
VisualBrush gridLines = new VisualBrush(gridCell);
gridLines.TileMode = TileMode.Tile;
gridLines.Viewport = new Rect(0, 0, 1.0 / numTileToAccumulate, 1.0 / numTileToAccumulate);
gridLines.AlignmentX = AlignmentX.Center;
gridLines.AlignmentY = AlignmentY.Center;
VisualBrush outerVB = new VisualBrush();
Rectangle outerRect = new Rectangle();
outerRect.Width = 10.0; //can be any size
outerRect.Height = 10.0;
outerRect.Fill = gridLines;
outerVB.Visual = outerRect;
outerVB.Viewport = new Rect(0, 0,
width * numTileToAccumulate, height * numTileToAccumulate);
outerVB.ViewportUnits = BrushMappingMode.Absolute;
outerVB.TileMode = TileMode.Tile;
this.Children.Remove(brdGrid);
brdGrid = new Border();
brdGrid.Height = this.Height;
brdGrid.Width = this.Width;
brdGrid.Background = outerVB;
this.Children.Add(brdGrid);
}
protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e)
{
base.OnMouseMove(e);
tbPos.Text = (_wBMP.PixelWidth / zoomLevel).ToString() + "," + (_wBMP.PixelHeight / zoomLevel).ToString() + " | " + Math.Ceiling((((Point)e.GetPosition(this)).X) / zoomLevel).ToString() + "," + Math.Ceiling((((Point)e.GetPosition(this)).Y / zoomLevel)).ToString();
if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
{
Point pos = e.GetPosition(this);
int xPos = (int)Math.Ceiling((pos.X) / zoomLevel);
int yPos = (int)Math.Ceiling((pos.Y) / zoomLevel);
int xDraw = (int)Math.Ceiling(pos.X);
int yDraw = (int)Math.Ceiling(pos.Y);
array[xPos, yPos] = 1;
drawing = true;
SetPixelsFromArray((int)zoomLevel);
//for (int i = 0; i < zoomLevel; i++)
//{
// for (int j = 0; j < zoomLevel; j++)
// {
// _wBMP.setPixel(xDraw, yDraw, cellColor);
// _dispImg.Source = _wBMP;
// }
//}
//_wBMP.setPixel(xPos, yPos, cellColor);
//_wBMP.setPixel((int)pos.X, (int)pos.Y, cellColor);
//_dispImg.Source = _wBMP;
}
}
private void SetPixelsFromArray(int ZoomLevel)
{
for (int i = 1; i < _wBMP.PixelWidth / ZoomLevel; i++)
{
for (int j = 1; j < _wBMP.PixelHeight / ZoomLevel; j++)
{
if (array[i, j] == 1)
{
for (int k = 0; k < ZoomLevel; k++)
{
for (int l = 0; l < ZoomLevel; l++)
{
_wBMP.setPixel((int)(i * ZoomLevel + k), (int)(j * ZoomLevel + l), cellColor);
_dispImg.Source = _wBMP;
}
}
}
}
}
}
protected override void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e)
{
//double d= this.ActualHeight;
//Double t =(double) this.GetValue(Canvas.TopProperty);
//double i = Convert.ToDouble(top);
getScreenRect();
if (e.ChangedButton == System.Windows.Input.MouseButton.Right)
{
if (cellColor == Colors.Black)
{
cellColor = Colors.Red;
}
else
{
cellColor = Colors.Black;
}
}
else if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
{
Point pos = e.GetPosition(this);
int xPos = (int)Math.Ceiling((pos.X) / zoomLevel);
int yPos = (int)Math.Ceiling((pos.Y) / zoomLevel);
array[xPos, yPos] = 1;
drawing = true;
SetPixelsFromArray((int)zoomLevel);
//_wBMP.setPixel((int)pos.X, (int)pos.Y, cellColor);
//_dispImg.Source = _wBMP;
}
}
private void getScreenRect()
{
Visual _rootVisual = HwndSource.FromVisual(this).RootVisual;
GeneralTransform transformToRoot = this.TransformToAncestor(_rootVisual);
Rect screenRect = new Rect(transformToRoot.Transform(new Point(0, 0)), transformToRoot.Transform(new Point(this.ActualWidth, this.ActualHeight)));
DependencyObject parent = VisualTreeHelper.GetParent(this);
while (parent != null)
{
Visual visual = parent as Visual;
System.Windows.Controls.Control control = parent as System.Windows.Controls.Control;
if (visual != null && control != null)
{
transformToRoot = visual.TransformToAncestor(_rootVisual);
Point pointAncestorTopLeft = transformToRoot.Transform(new Point(0, 0));
Point pointAncestorBottomRight = transformToRoot.Transform(new Point(control.ActualWidth, control.ActualHeight));
Rect ancestorRect = new Rect(pointAncestorTopLeft, pointAncestorBottomRight);
screenRect.Intersect(ancestorRect);
}
parent = VisualTreeHelper.GetParent(parent);
//}
// at this point screenRect is the bounding rectangle for the visible portion of "this" element
}
// return screenRect;
}
protected override void OnMouseWheel(System.Windows.Input.MouseWheelEventArgs e)
{
base.OnMouseWheel(e);
if (e.Delta > 0)
{
zoomLevel *= 2;
}
else
{
zoomLevel /= 2;
}
if (zoomLevel > 8)
{
zoomLevel = 8;
}
if (zoomLevel <= 1)
{
zoomLevel = 1;
// brdGrid.Visibility = Visibility.Collapsed;
}
else
{
//brdGrid.Visibility = Visibility.Visible;
}
_wBMP = new WriteableBitmap((int)zoomLevel * canvasWidth, (int)zoomLevel * canvasHeight, 96, 96, PixelFormats.Bgr32, BitmapPalettes.WebPalette);
_wBMP.setPixel(Colors.White);
this.Width = zoomLevel * canvasWidth;
this.Height = zoomLevel * canvasHeight;
if (drawing == true)
{
SetPixelsFromArray((int)zoomLevel);
}
//this.InvalidateVisual();
}
internal bool SaveAsBMP(string fileName)
{
return true;
}
}
public static class bitmapextensions
{
public static void setPixel(this WriteableBitmap wbm, Color c)
{
if (!wbm.Format.Equals(PixelFormats.Bgr32))
return;
wbm.Lock();
IntPtr buff = wbm.BackBuffer;
int Stride = wbm.BackBufferStride;
int x = 0;
int y = 0;
for (x = 0; x < wbm.PixelWidth; x++)
{
for (y = 0; y < wbm.PixelHeight; y++)
{
unsafe
{
byte* pbuff = (byte*)buff.ToPointer();
int loc = y * Stride + x * 4;
pbuff[loc] = c.B;
pbuff[loc + 1] = c.G;
pbuff[loc + 2] = c.R;
//pbuff[loc + 3] = c.A;
}
}
}
wbm.AddDirtyRect(new Int32Rect(0, 0, x, y));
wbm.Unlock();
}
public static void setPixel(this WriteableBitmap wbm, int x, int y, Color c)
{
if (y > wbm.PixelHeight - 1 || x > wbm.PixelWidth - 1)
return;
if (y < 0 || x < 0)
return;
if (!wbm.Format.Equals(PixelFormats.Bgr32))
return;
wbm.Lock();
IntPtr buff = wbm.BackBuffer;
int Stride = wbm.BackBufferStride;
unsafe
{
byte* pbuff = (byte*)buff.ToPointer();
int loc = y * Stride + x * 4;
pbuff[loc] = c.B;
pbuff[loc + 1] = c.G;
pbuff[loc + 2] = c.R;
//pbuff[loc + 3] = c.A;
}
wbm.AddDirtyRect(new Int32Rect(x, y, 1, 1));
wbm.Unlock();
}
public static Color getPixel(this WriteableBitmap wbm, int x, int y)
{
if (y > wbm.PixelHeight - 1 || x > wbm.PixelWidth - 1)
return Color.FromArgb(0, 0, 0, 0);
if (y < 0 || x < 0)
return Color.FromArgb(0, 0, 0, 0);
if (!wbm.Format.Equals(PixelFormats.Bgr32))
return Color.FromArgb(0, 0, 0, 0);
IntPtr buff = wbm.BackBuffer;
int Stride = wbm.BackBufferStride;
Color c;
unsafe
{
byte* pbuff = (byte*)buff.ToPointer();
int loc = y * Stride + x * 4;
c = Color.FromArgb(pbuff[loc + 3], pbuff[loc + 2], pbuff[loc + 1], pbuff[loc]);
}
return c;
}
}
}
You should implement IScrollInfo on your canvas (or actually, create a custom Panel that inherits from Canvas and implements IScrollInfo).
That interface holds all that is relevant to your situation:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.iscrollinfo.aspx
http://blogs.msdn.com/b/jgoldb/archive/2008/03/08/performant-virtualized-wpf-canvas.aspx

RGB Parade in WPF

I'm supposed to create this RBG parade project in WPF, but I have no idea where to start. It should handle images in 720p settings (1280x720). Any idea on where to start, I'm completely clueless. I don't want the whole project just a few pointers.
Thank you.
Ok, this is what I came up with, I'm sure there's a better solution but it works:
public ObservableCollection<double> RPercentPerColumn { get; set; }
public ObservableCollection<double> GPercentPerColumn { get; set; }
public ObservableCollection<double> BPercentPerColumn { get; set; }
private int[] GetImagePixels(ref int imageHeight, ref int imageWidth)
{
BitmapImage image = new BitmapImage(new Uri(this.CurrentImageFile, UriKind.Absolute));
WriteableBitmap bmp = new WriteableBitmap(image);
int rows = bmp.PixelHeight;
int columns = bmp.PixelWidth;
int[] pixels = new int[bmp.PixelWidth * bmp.PixelHeight];
bmp.CopyPixels(pixels, columns * 4, 0);
imageHeight = bmp.PixelHeight;
imageWidth = bmp.PixelWidth;
return pixels;
}
private void ClearAllData()
{
this.RPercentPerColumn.Clear();
this.GPercentPerColumn.Clear();
this.BPercentPerColumn.Clear();
}
public void ProcessRGBParade()
{
if (string.IsNullOrEmpty(this.CurrentImageFile))
return;
ClearAllData();
int columns = 0;
int rows = 0;
int[] pixels = GetImagePixels(ref rows, ref columns);
int column = 0;
int row = 0;
int redColumnTotal = 0;
int greenColumnTotal = 0;
int blueColumnTotal = 0;
int currentPixel = 0;
double totalColorInColumn = 0;
double redIntensity = 0;
double greenIntensity = 0;
double blueIntensity = 0;
int r = 0;
int g = 0;
int b = 0;
// logic to calculate intensity
for (int i = 0; i < pixels.Length; i ++)
{
row++;
r = (pixels[currentPixel] & 0x00FF0000) >> 16;
g = (pixels[currentPixel] & 0x0000FF00) >> 8;
b = (pixels[currentPixel] & 0x000000FF);
redColumnTotal += r;
greenColumnTotal += g;
blueColumnTotal += b;
totalColorInColumn += r + g + b;
if (row == rows)
{
row = 0;
column++;
currentPixel = column;
redIntensity = (redColumnTotal / totalColorInColumn) * 100;
greenIntensity = (greenColumnTotal / totalColorInColumn) * 100;
blueIntensity = (blueColumnTotal / totalColorInColumn) * 100;
RPercentPerColumn.Add(double.IsNaN(redIntensity) ? 0 : redIntensity);
GPercentPerColumn.Add(double.IsNaN(greenIntensity) ? 0 : greenIntensity);
BPercentPerColumn.Add(double.IsNaN(blueIntensity) ? 0 : blueIntensity);
redColumnTotal = 0;
greenColumnTotal = 0;
blueColumnTotal = 0;
totalColorInColumn = 0;
}
else
{
currentPixel += columns;
}
}
}

Resources