How to Change Opacity of outside Rectangle? - windows-phone-8

In my case i want to change the opacity of the video brush using Rectangle. Rectangle area should have Transparent and out side rectangle should have semi Transparent. I don't know how to do this. I need some sample for this.
Thanks in advance
Edit:
I have tried Grid row and column definition . like this
<Grid Background="Transparent" Name="OuterGrid">
<Grid.RowDefinitions>
<RowDefinition Height="211*"/>
<RowDefinition Height="308"/>
<RowDefinition Height="249*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle
Stroke="Red"
StrokeThickness="4"
Fill="LightGray"
Grid.Row="1"
Grid.Column="1" />
<Rectangle
MouseMove="Rectangle_MouseMove_TopLeft"
MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"
MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"
Stroke="Yellow"
Canvas.ZIndex="1"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Height="30"
Width="30"
StrokeThickness="4" Grid.Row="1"
Fill="Red"
Grid.Column="1" />
<Rectangle
MouseMove="Rectangle_MouseMove_TopRight"
Stroke="Yellow"
MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"
MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"
Canvas.ZIndex="1"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Height="30"
Width="30"
StrokeThickness="4" Grid.Row="1"
Fill="Red"
Grid.Column="1" />
<Rectangle
MouseMove="Rectangle_MouseMove_BottomLeft"
Stroke="Yellow"
MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"
MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"
Canvas.ZIndex="1"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Height="30"
Width="30"
StrokeThickness="4" Grid.Row="1"
Fill="Red"
Grid.Column="1" />
<Rectangle
MouseMove="Rectangle_MouseMove_BottomLeft"
Stroke="Yellow"
MouseLeftButtonDown="Rectangle_MouseLeftButtonDown"
MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"
Canvas.ZIndex="1"
HorizontalAlignment="Right"
Width="30"
StrokeThickness="4" Grid.Row="1"
Fill="Red"
Grid.Column="1" Margin="0,278,0,0" />
</Grid>
c#
private void Rectangle_MouseMove_TopLeft(object sender, MouseEventArgs e)
{
if (isMove)
{
Point p = e.GetPosition(this.OuterGrid);
double pX = point.X - p.X;
double pY = point.Y - p.Y;
double w = OuterGrid.ColumnDefinitions.ElementAt(1).ActualWidth + pX;
double h = OuterGrid.RowDefinitions.ElementAt(1).ActualHeight + pY;
//if (pX < w)
//{
// OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(w + (w - pX), GridUnitType.Pixel);
//}
//else
//{
// OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(w - (w - pX), GridUnitType.Pixel);
//}
//if (pY < h)
//{
// OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(h + (h - pY), GridUnitType.Pixel);
//}
//else
//{
// OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(h - (h - pY), GridUnitType.Pixel);
//}
OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(h, GridUnitType.Pixel);
OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(w, GridUnitType.Pixel);
}
}
private void Rectangle_MouseMove_TopRight(object sender, MouseEventArgs e)
{
if (isMove)
{
Point p = e.GetPosition(this.OuterGrid);
double pX = p.X;
double pY = p.Y;
double w = OuterGrid.ColumnDefinitions.ElementAt(1).ActualWidth;
double h = OuterGrid.RowDefinitions.ElementAt(1).ActualHeight;
OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(p.Y, GridUnitType.Pixel);
OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(pX, GridUnitType.Pixel);
}
}
private void Rectangle_MouseMove_BottomLeft(object sender, MouseEventArgs e)
{
if (isMove)
{
Point p = e.GetPosition(this.OuterGrid);
double pX = p.X - point.X;
double pY = p.Y -point.Y;
double w = OuterGrid.ColumnDefinitions.ElementAt(1).ActualWidth + pX;
double h = OuterGrid.RowDefinitions.ElementAt(1).ActualHeight + pY;
OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(h, GridUnitType.Pixel);
OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(w, GridUnitType.Pixel);
}
}
private void Rectangle_MouseMove_BottomRight(object sender, MouseEventArgs e)
{
if (isMove)
{
Point p = e.GetPosition(this.OuterGrid);
double pX = p.X;
double pY = p.Y;
double w = OuterGrid.ColumnDefinitions.ElementAt(1).ActualWidth;
double h = OuterGrid.RowDefinitions.ElementAt(1).ActualHeight;
OuterGrid.RowDefinitions.ElementAt(1).Height = new GridLength(p.Y, GridUnitType.Pixel);
OuterGrid.ColumnDefinitions.ElementAt(1).Width = new GridLength(pX, GridUnitType.Pixel);
}
}
private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isMove = true;
point = e.GetPosition(this.OuterGrid);
}
private void Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isMove = false;
}
I need smooth motion on this.
Pls fine tune this code

I'm not 100% sure of what you want to achieve exactly (e.g. what video brush are you referring to?), but I attempted it anyway.
I'm guessing you want WP 8 not WP 8.1 (based on your original code).
Outside region is darkened while region inside the rectangle remains untouched. I'm not 100% sure if it's possible to invert an element's Clip or OpacityMask, so the way I achieved this is kind of hacky.
Your original code was very buggy, not DRY, and the handles didn't resize properly so I fixed that.
Final result
XAML
<Grid x:Name="LayoutRoot">
<Grid.Background>
<ImageBrush ImageSource="/Assets/Image.jpg" Stretch="None" />
</Grid.Background>
<Grid x:Name="OuterRect">
<Grid.Resources>
<Style x:Key="HandleStyle" TargetType="Rectangle">
<Setter Property="Width" Value="30" />
<Setter Property="Height" Value="30" />
<Setter Property="StrokeThickness" Value="4" />
<Setter Property="Stroke" Value="Red" />
<Setter Property="Fill" Value="Yellow" />
</Style>
</Grid.Resources>
<Rectangle Fill="Black" Opacity="0.6" />
<Grid x:Name="Rect" Width="300" Height="400">
<Rectangle Stroke="Red" StrokeThickness="4">
<Rectangle.Fill>
<ImageBrush ImageSource="/Assets/Image.jpg" Stretch="None" />
</Rectangle.Fill>
</Rectangle>
<Rectangle
x:Name="HandleTopLeft"
Style="{StaticResource HandleStyle}"
MouseMove="Handle_MouseMove"
MouseLeftButtonDown="Handle_MouseLeftButtonDown"
MouseLeftButtonUp="Handle_MouseLeftButtonUp"
HorizontalAlignment="Left"
VerticalAlignment="Top" />
<Rectangle
x:Name="HandleTopRight"
Style="{StaticResource HandleStyle}"
MouseMove="Handle_MouseMove"
MouseLeftButtonDown="Handle_MouseLeftButtonDown"
MouseLeftButtonUp="Handle_MouseLeftButtonUp"
HorizontalAlignment="Right"
VerticalAlignment="Top" />
<Rectangle
x:Name="HandleBottomLeft"
Style="{StaticResource HandleStyle}"
MouseMove="Handle_MouseMove"
MouseLeftButtonDown="Handle_MouseLeftButtonDown"
MouseLeftButtonUp="Handle_MouseLeftButtonUp"
HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Rectangle
x:Name="HandleBottomRight"
Style="{StaticResource HandleStyle}"
MouseMove="Handle_MouseMove"
MouseLeftButtonDown="Handle_MouseLeftButtonDown"
MouseLeftButtonUp="Handle_MouseLeftButtonUp"
HorizontalAlignment="Right"
VerticalAlignment="Bottom" />
</Grid>
</Grid>
</Grid>
C# code-behind
const double MIN_RECT_WIDTH = 80;
const double MIN_RECT_HEIGHT = 80;
bool isDragging;
Point startPoint;
Size startSize;
private void Handle_MouseMove(object sender, MouseEventArgs e)
{
if (!isDragging)
return;
var handle = (Rectangle)sender;
var p = e.GetPosition(null);
var deltaX = p.X - startPoint.X;
var deltaY = p.Y - startPoint.Y;
if (handle == HandleTopLeft || handle == HandleBottomLeft) deltaX = -deltaX;
if (handle == HandleTopLeft || handle == HandleTopRight) deltaY = -deltaY;
Rect.Width = Math.Min(OuterRect.ActualWidth, Math.Max(MIN_RECT_WIDTH, startSize.Width + deltaX * 2));
Rect.Height = Math.Min(OuterRect.ActualHeight, Math.Max(MIN_RECT_HEIGHT, startSize.Height + deltaY * 2));
}
private void Handle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var handle = (Rectangle)sender;
handle.CaptureMouse();
isDragging = true;
startPoint = e.GetPosition(null);
startSize = Rect.RenderSize;
}
private void Handle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var handle = (Rectangle)sender;
handle.ReleaseMouseCapture();
isDragging = false;
}

Related

Creation of heat map(spectrogram) using Winrt xaml toolkit multiple line series

I am creating heat maps in Windows store apps 8.1 using algorithm provided in stack overflow.
first approach:
public Color HeatMapColor(decimal value, decimal min, decimal max)
{
decimal val = (value - min) / (max - min);
int r = Convert.ToByte(255 * val);
int g = Convert.ToByte(255 * (1 - val));
int b = 0;
return Color.FromArgb(255,r,g,b);
}
second approach:
public Brush getColourTemp(int maxVal,int minVal ,double actual )
{
int maxVal = 70000000;
int minVal = 100000;
var midVal = (maxVal - minVal) / 2;
int intR;
int intG;
int intB = Convert.ToInt32(Math.Round(0.0));
if (actual >= midVal)
{
intR = 255;
intG = Convert.ToInt32(Math.Round(255 * ((maxVal - actual) / (maxVal - midVal))));
}
else
{
intG = 255;
intR = Convert.ToInt32(Math.Round(255 * ((actual) - minVal) / (midVal - minVal)));
}
// Color background = Color.FromArgb(255, (byte)ran.Next(255), (byte)ran.Next(255), (byte)ran.Next(255));
Color background = Color.FromArgb(255, (byte)intR, (byte)intG, (byte)intB);
return new SolidColorBrush(background);
//byte[] bytes = BitConverter.GetBytes(actual);
//return new SolidColorBrush(Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]));
// return to_rgb(intR, intG, intB);
}
But in both the case blue colour is zero why. I need blue color in heat map also can any one help me out.
I am creating heat map using Winrt xaml toolkit line graphs
code details
for (int i = 0; i <= 200; i++)
{`enter code here`
if (i > 25)
{
LineChart.Series.RemoveAt(0);
}
List<FinancialStuff> financialStuffList = new List<FinancialStuff>();
LineSeries line = new LineSeries();
line.Title = "";
line.IndependentValuePath = "Name";
line.DependentValuePath = "Amount";
for (int j = 0; j < 256; j++)
{
financialStuffList.Add(new FinancialStuff() { Name = i, Amount = j - 130, FavoriteColor = ConvertTotalToRgb(i, j) });
}
line.ItemsSource = financialStuffList;
line.DataPointStyle = style;
LineChart.Series.Add(line);
if (i >= 25)
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
//******************************************************************************
public Brush ConvertTotalToRgb(int val, int val1)
{`enter code here`
double actual = 0.0;
int range = 70000000 - 100000;
actual = data[val, val1];
int main = Convert.ToInt32(255 * actual / range);
string hexR = main.ToString("X2");
int flip = Convert.ToInt32(255 * (1 - (actual / range)));
string hexB = flip.ToString("X2");
string colorValue = "#" + hexR + "00" + hexB;
byte R = Convert.ToByte(colorValue.Substring(1, 2), 16);
byte G = Convert.ToByte(colorValue.Substring(3, 2), 16);
byte B = Convert.ToByte(colorValue.Substring(5, 2), 16);
Color background = Color.FromArgb((byte)255, R, G, B);
return new SolidColorBrush(background);
}
}
very bad performance after i=50 it is very slow and not loading may be performance issue of in line graphs as it is huge number.
Please help if any body can tell improvement or suggests other ways to create Spectrogram in windows store apps 8.1 development.
XAML page
<Page xmlns:Charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"
x:Class="MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Spect"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid >
<Grid.Resources>
<Style
x:Key="ColorByPreferenceColumn"
x:Name="abc"
TargetType="Charting:LineDataPoint">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate
TargetType="Charting:LineDataPoint">
<Grid Background="{Binding FavoriteColor}">
<Polygon>
<Polygon.Fill>
<LinearGradientBrush>
<GradientStop Color="#77ffffff" Offset="0"/>
<GradientStop Color="#00ffffff" Offset="1"/>
</LinearGradientBrush>
</Polygon.Fill>
</Polygon>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Charting:Chart x:Name="LineChart" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300" Height="600" Margin="208,107,0,0">
</Charting:Chart>
<Button Content="Data" HorizontalAlignment="Left" Margin="175,31,0,0" VerticalAlignment="Top" Click="Button_Click"/>
</Grid>

Windows phone columns and grids during orientation change

Hey people I have this in my xml
<Grid x:Name="LayoutRoot" Background="Black">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="72"/>
<RowDefinition Height="*"/>
<RowDefinition Height="90"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="72"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="90"/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="FirstBorder" Background="Red" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="3"/>
<Grid Grid.Column="1" Grid.Row="0" Grid.RowSpan="3" x:Name="LivePreviewTapTarget">
<Canvas>
<Rectangle x:Name="CameraRectangle" Width="638" Height="480" Fill="{Binding PreviewBrush}">
<Rectangle.RenderTransform>
<CompositeTransform x:Name="LivePreviewTransform"/>
</Rectangle.RenderTransform>
</Rectangle>
</Canvas>
</Grid>
<Border x:Name="SecondBorder" Background="Yellow" Grid.Column="2" Grid.Row="0" Grid.RowSpan="3"></Border>
And even this red panel is in first column only, when I run the app, it expands somehow (you can see that on the image attached, there is red border over camera view). What am I doing wrong?
NEW PROBLEM!
When I change page rotation I get this in portrait view. The xaml of the page is the same. And I do this in OnOrientationChanged event handler.
if (IsPortrait(Orientation))
{
Grid.SetRow(FirstBorder, 0);
Grid.SetColumn(FirstBorder, 0);
Grid.SetColumnSpan(FirstBorder, 3);
Grid.SetRow(LivePreviewTapTarget, 1);
Grid.SetColumn(LivePreviewTapTarget, 0);
Grid.SetColumnSpan(LivePreviewTapTarget, 3);
Grid.SetRow(SecondBorder, 2);
Grid.SetColumn(SecondBorder, 0);
Grid.SetColumnSpan(SecondBorder, 3);
CameraRectangle.Width = 480;
CameraRectangle.Height = 638;
}
else
{
Grid.SetColumn(FirstBorder, 0);
Grid.SetRow(FirstBorder, 0);
Grid.SetRowSpan(FirstBorder, 3);
Grid.SetColumn(SecondBorder, 2);
Grid.SetRow(SecondBorder, 0);
Grid.SetRowSpan(SecondBorder, 3);
Grid.SetColumn(LivePreviewTapTarget, 1);
Grid.SetRow(LivePreviewTapTarget, 0);
Grid.SetRowSpan(LivePreviewTapTarget, 3);
CameraRectangle.Width = 638;
CameraRectangle.Height = 480;
}
if (IsPortrait(Orientation))
{
_livePreviewTransform.Rotation = _viewModel.ViewfinderRotation;
_livePreviewTransform.CenterX = 240;
_livePreviewTransform.CenterY = 400;
_livePreviewTransform.TranslateX = -100;
_livePreviewTransform.TranslateY = -160;
}
else if (Orientation == PageOrientation.LandscapeRight)
{
_livePreviewTransform.Rotation = 180;
_livePreviewTransform.CenterX = 400;
_livePreviewTransform.CenterY = 240;
_livePreviewTransform.TranslateX = -160;
_livePreviewTransform.TranslateY = 0;
}
else
{
_livePreviewTransform.Rotation = 0;
_livePreviewTransform.CenterX = 400;
_livePreviewTransform.CenterY = 240;
_livePreviewTransform.TranslateX = 0;
_livePreviewTransform.TranslateY = 0;
}
var scaleX = 1.0;
if (_viewModel.CameraSensorLocation == CameraSensorLocation.Front)
scaleX = -1.0;
_livePreviewTransform.ScaleX = scaleX;
Here is the page look in portrait mode.
Strange, I've tested your code on my HTC 8X and it works just fine. Maybe the red color is already part of the PhotoCamera stream on your device?
As a workaround I'd recommend adding few pixels of negative margin to the the CameraRectangle element, that should hide the red borders.

Flex UI Components disappear

I've implemented a method to change display size.
When I click on maximize, I reposition some buttons in a viewstack.
Problem is when I restore view the buttons disappear.
Can someone help me?
{
nativeWindow.addEventListener(NativeWindowBoundsEvent.RESIZING, onAppResize);
nativeWindow.addEventListener(NativeWindowBoundsEvent.RESIZE, onAppResize);
nativeWindow.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,onAppMaximized);
var screenBounds:Rectangle = Screen.mainScreen.bounds;
nativeWindow.x = 10;
nativeWindow.y = 10;
}
private function onAppMaximized(e:NativeWindowDisplayStateEvent):void
{
if(String(e.afterDisplayState) == "maximized" && DisplayMaximized == false)
{
e.preventDefault();
nativeWindow.x = 10;
nativeWindow.y = 10;
AppImageWidth = 1280;
AppImageHeight = 900;
nativeWindow.width = 1280;
nativeWindow.height = 900;
viewstack.createComponentsFromDescriptors(true);
viewstackBuchungen.width = 1206;
viewstackBuchungen.height = 600;
Button.x = 1135;
Button.y = 608;
Button2.x = 1135;
Button2.y = 608;
DisplayMaximized = true;
}
else if(String(e.afterDisplayState) == "maximized" && DisplayMaximized == true)
{
e.preventDefault();
AppImageWidth = 1024;
AppImageHeight = 600;
nativeWindow.width = 1024;
nativeWindow.height = 600;
viewstackBuchungen.width = 950;
viewstackBuchungen.height = 313;
Button.x = 879;
Button.y = 321;
Button2.x = 879;
Button2.y = 321;
DisplayMaximized = false;
}
}
thanks for your answer.
I tried moving them with .move(x,y).
Nothing changed...
The buttons are on same position, because they are in different navigator content.
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="init();" width="1024" height="600">
private function init():void
{
nativeWindow.addEventListener(NativeWindowBoundsEvent.RESIZING, onAppResize);
nativeWindow.addEventListener(NativeWindowBoundsEvent.RESIZE, onAppResize);
nativeWindow.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,onAppMaximized);
nativeWindow.x = 10;
nativeWindow.y = 10;
}
private function onAppResize(e:NativeWindowBoundsEvent):void
{
e.preventDefault();
}
private function onAppMaximized(e:NativeWindowDisplayStateEvent):void
{
if(String(e.afterDisplayState) == "maximized" && DisplayMaximized == false)
{
e.preventDefault();
nativeWindow.x = 10;
nativeWindow.y = 10;
nativeWindow.width = 1280;
nativeWindow.height = 900;
viewstack1.createComponentsFromDescriptors(true);
viewstack1.width = 1206;
viewstack1.height = 600;
button1.move(1135,608);
button2.move(1135,608);
DD1.move(1082,608);
DisplayMaximized = true;
}
else if(String(e.afterDisplayState) == "maximized" && DisplayMaximized == true)
{
e.preventDefault();
nativeWindow.width = 1024;
nativeWindow.height = 600;
viewstack1.width = 950;
viewstack1.height = 313;
button1.move(879,321);
button2.move(879,321);
DD1.move(826,321);
DisplayMaximized = false;
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Platzieren Sie nichtvisuelle Elemente (z. B. Dienste, Wertobjekte) hier -->
</fx:Declarations>
<s:Group x="16" y="113" width="1254" height="463">
<mx:ViewStack id="viewstack1" x="0" y="24" width="950" height="313" selectedIndex="0" creationPolicy="all">
<s:NavigatorContent width="100%" height="100%" label="Nav1" id="nav1" creationPolicy="all">
<mx:AdvancedDataGrid id="grid1" x="0" y="0" width="100%" height="100%"
designViewDataType="flat"
editable="true" horizontalScrollPolicy="off"
sortableColumns="false" resizableColumns="false" draggableColumns="false">
<mx:columns>
<mx:AdvancedDataGridColumn dataField="test1" headerText="test1" width="35"/>
</mx:columns>
</mx:AdvancedDataGrid>
<s:Button x="879" y="321" label="Button1" id="button1"/>
</s:NavigatorContent>
<s:NavigatorContent width="100%" height="100%" label="Nav2" id="nav2" creationPolicy="all">
<mx:AdvancedDataGrid id="grid2" x="0" y="0" width="100%" height="100%"
designViewDataType="flat"
editable="true" horizontalScrollPolicy="off"
sortableColumns="false" resizableColumns="false" draggableColumns="false">
<mx:columns>
<mx:AdvancedDataGridColumn dataField="test2" headerText="test2" width="35"/>
</mx:columns>
</mx:AdvancedDataGrid>
<s:Button x="879" y="321" label="Button2" id="button2" />
</s:NavigatorContent>
<s:NavigatorContent width="100%" height="100%" label="Nav3" id="nav3" creationPolicy="all">
<mx:AdvancedDataGrid id="grid3" x="0" y="0" width="100%" height="100%"
designViewDataType="flat"
editable="true" horizontalScrollPolicy="off"
sortableColumns="false" resizableColumns="false" draggableColumns="false">
<mx:columns>
<mx:AdvancedDataGridColumn dataField="test3" headerText="test3" width="35"/>
</mx:columns>
</mx:AdvancedDataGrid>
<s:DropDownList x="826" id="DD1" y="321" width="125" prompt="DD1" alpha="1"/>
</s:NavigatorContent>
</mx:ViewStack>
<s:TabBar x="0" y="0" dataProvider="{viewstack1}" />
</s:Group>

Silverlight ScrollViewer not updating after zoom

I have a Silverlight grid with a bunch of content in it (rectangles, textBlocks, etc.) which represents content in a room. Because it gets pretty complex, I decided I needed an ability to "zoom-in" on the grid. I found some good code to do that, but the problem is that after zooming the grids associated ScrollViewer doesn't scroll the full distance down or to the right. How can I force it to update so that I can scroll to the bottom and all the way to the right?
If it helps, here's the code to permit zooming of my Grid:
var style = new Style(typeof(Grid));
var scale = new ScaleTransform();
scale.CenterX = .5;
scale.CenterY =.5;
scale.ScaleX = Scale;
scale.ScaleY = Scale;
var rs = new Setter();
rs.Property = DataGridCell.RenderTransformProperty;
rs.Value = scale;
style.Setters.Add(rs);
OtdrPatchLocationGrid.Style = style;
and here is the XAML that shows the grid and the scroll viewer
<ScrollViewer Name="scViewer" Grid.Row="1" Visibility="Visible" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
<Grid x:Name="OtdrPatchLocationGrid" MinHeight="350" VerticalAlignment="Stretch" Background="Yellow" Grid.Row="1" Grid.Column="0" Margin="0" MouseDown="OtdrRackViewer_MouseDown">
</Grid>
</ScrollViewer>
I'm working on the same issue now,
the ScrollViewer is affected only by the change in Width or Height,
so to fix the problem, you have to do as the following:
suppose we got the Grid or Canvas named (ZoomCanvas)
in the code behind:
double initialCanvasHeight;
double initialCanvasWidth;
public void MainPage() //As the Constructor
{
initialCanvasHeight = ZoomCanvas.Height;
initialCanvasWidth = ZoomCanvas.Width;
}
ZoomCanvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
/*Assuming you have the scaling code here and the object CanvasScale is used to scale the canvas*/
foreach (var node in ZoomCanvas)
{
var nodeTop = Canvas.GetTop(node);
var nodeLeft = Canvas.GetLeft(node);
if(mostTopValue < nodeTop)
mostTopValue = nodeTop;
if(mostLeftValue < nodeLeft)
mostLeftValue = nodeLeft;
var desiredHeight = (mostTopValue + NodeHeight)*canvasScale.ScaleY;
var desiredWidth = (mostLeftValue + NodeWidth) * canvasScale.ScaleX;
if (desiredHeight > canvasInitialHeight)
{
while (heightToIncrease < desiredHeight)
heightToIncrease += 10;
ZoomCanvas.Height = heightToIncrease;
}
else
while (ZoomCanvas.Height > canvasInitialHeight)
ZoomCanvas.Height -= 10;
if (desiredWidth > canvasInitialWidth)
{
while (widthToIncrease < desiredWidth)
widthToIncrease += 10;
ZoomCanvas.Width = widthToIncrease;
}
else while (ZoomCanvas.Height > canvasInitialHeight)
ZoomCanvas.Width -= 10;
}
scrollViewer.UpdateLayout();
}

Tic Tac Toe Game in Flex

I am newer in FLEX and currently i am using FLEX 3.0
I want to develop a Tic Tac Toe game in FLEX. At first i think this one is the easiest for me but now its going to be very tough for me. I have searched on Internet but not a single link helps me that much so please give me proper Idea with proper code. Here i am giving you the sample code. its a bit of complex so sorry for that.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="#000000"
horizontalAlign="center" verticalAlign="middle" height="100%" width="100%" verticalGap="0" horizontalGap="0">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.controls.Image;
private var blnFirst:Boolean = true;
private var arr0:Array = new Array();
private var arr1:Array = new Array();
private var arr2:Array = new Array();
private var count:int = 0;
private var arr:Array = new Array();
private var pl1Won:Boolean = false;
private var pl2Won:Boolean = false;
public function img_click(event:Event):void
{
if(event.currentTarget.enabled)
{
count++;
if(blnFirst)
{
blnFirst = false;
var itemp:Image = new Image();
itemp.percentHeight = 100;
itemp.percentWidth = 100;
itemp.source = "Images/Circle.png";
event.currentTarget.addChild(itemp);
event.currentTarget.enabled = false;
arrayInsert(event.currentTarget.id,true);
}
else
{
blnFirst = true;
var itemp:Image = new Image();
itemp.percentHeight = 100;
itemp.percentWidth = 100;
itemp.source = "Images/Cross.png";
event.currentTarget.addChild(itemp);
event.currentTarget.enabled = false;
arrayInsert(event.currentTarget.id,false);
}
}
if(count == 9)
{
arr = [arr0, arr1, arr2];
}
}
private function arrayInsert(id:String,value:Boolean):void
{
if(id == "box00")
arr0[0] = value;
if(id == "box01")
arr0[1] = value;
if(id == "box02")
arr0[2] = value;
if(id == "box10")
arr1[0] = value;
if(id == "box11")
arr1[1] = value;
if(id == "box12")
arr1[2] = value;
if(id == "box20")
arr2[0] = value;
if(id == "box21")
arr2[1] = value;
if(id == "box22")
arr2[2] = value;
}
private function btn_click():void
{
for(var i:int=0;i<3;i++)
{
for(var j:int=0;j<3;j++)
{
//very confused in this part
}
}
}
]]>
</mx:Script>
<mx:VBox height="500" width="500" borderStyle="solid" borderThickness="3" borderColor="#000000"
backgroundColor="#ffffff" verticalGap="0" horizontalGap="0">
<mx:HBox width="100%" height="33.3%" horizontalGap="0" verticalGap="0">
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box00" >
</mx:Box>
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box01">
</mx:Box>
<mx:Box height="100%" width="33.4%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box02">
</mx:Box>
</mx:HBox>
<mx:HBox width="100%" height="33.3%" horizontalGap="0" verticalGap="0">
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box10">
</mx:Box>
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box11">
</mx:Box>
<mx:Box height="100%" width="33.4%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box12">
</mx:Box>
</mx:HBox>
<mx:HBox width="100%" height="33.4%" horizontalGap="0" verticalGap="0">
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box20">
</mx:Box>
<mx:Box height="100%" width="33.3%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box21">
</mx:Box>
<mx:Box height="100%" width="33.4%" borderStyle="solid" borderThickness="3" borderColor="#000000" backgroundColor="#ffffff"
click="{img_click(event);}" id="box22">
</mx:Box>
</mx:HBox>
</mx:VBox>
<mx:Button click="{btn_click();}" />
</mx:Application>
I have check the winning condition on btn_click() function but you can give me the idea to change it when the one row is completed.
I want to know how to handle the array of TicTacToe Game.
Assuming that you are creating a tic tac toe of 3x3 grid.
Create a two dimensional array for better visualization.
Initialize them to 0.
Each time a 0 is entered at a[i,j] assign -1 to a[i,j] if empty
Check the ith row and jth column for sum -3, also if i=j or i+j=2 check for diagonals to have sum -3, you have a winner.
Each time a X is entered at a[i,j] assign 1 to a[i,j] if empty
Check the ith row and jth column for sum 3, also if i=j or i+j=2 check for diagonals to have sum 3, you have a winner
This game can develop using different Logic.
Refer 1 and 2 Which source enabled.
and try to accomplish your game.
The below was written as an assignment for students (total beginners)
The classwork: http://code.google.com/p/as3-workshop/source/browse/#svn%2Ftrunk%2Fsrc%2Ftld%2Fcourse%2Flesson1 (the game played by the player herself consequently taking sides of "O" and "X".
The homework: http://code.google.com/p/as3-workshop/source/browse/#svn%2Ftrunk%2Fsrc%2Ftld%2Fcourse%2Fhomework1 (the computer plays against the human).
The examples aren't very well documented (we did commenting and explanation in class, which I didn't record), but considering there's not much code, you should get through it.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Graphics;
import flash.text.TextField;
import flash.text.TextFormat;
/**
* ...
* #author Jeet Chauhan
*/
public class TicTacToe extends Sprite
{
private var crossTurn:Boolean = true;
private var rects:Vector.<Rect>;
var currentMove:Number = 0;
public function TicTacToe()
{
createBoard();
}
private function createBoard():void
{
var g:flash.display.Graphics = this.graphics;
g.lineStyle(2, 0x000000);
g.beginFill(0xffff00);
g.drawRect(10, 10, 190, 190);
rects = new Vector.<Rect>();
var r:Rect
for (var i:int = 0; i < 9; i++)
{
r = new Rect();
this.addChild(r);
r.id = i;
r.y = 20 + Math.floor(i % 3) * 60;
r.x = 20 + Math.floor(i / 3) * 60;
r.addEventListener(MouseEvent.CLICK, moveNextTurn);
rects.push(r);
}
}
private function moveNextTurn(e:MouseEvent):void
{
var target:Rect = e.target as Rect
target.removeEventListener(MouseEvent.CLICK, moveNextTurn);
var turn:Sprite;
if (crossTurn) {
turn = target.addChild(new Cross) as Sprite;
target.occupied = "X";
} else {
turn = target.addChild(new Circle) as Sprite;
target.occupied = "O";
}
turn.x = 15;
turn.y = 15;
currentMove++;
if (currentMove > 4) checkAnswer();
crossTurn = !crossTurn;
}
private function checkAnswer():void
{
var winner:String = "_";
for (var i:int = 0, j = 0; i < 9; i += 3, j++)
{
if ((rects[i].occupied != "_") && (rects[i].occupied == rects[i+1].occupied) && (rects[i+1].occupied == rects[i+2].occupied))
{
winner = rects[i].occupied;
}
if ((rects[j].occupied != "_") && (rects[j].occupied == rects[j+3].occupied) && (rects[j+6].occupied == rects[j+3].occupied))
{
winner = rects[j].occupied;
}
}
if(rects[4].occupied != "_"){
if ((rects[0].occupied == rects[4].occupied) && (rects[8].occupied == rects[4].occupied))
{
winner = rects[0].occupied;
}
if ((rects[2].occupied == rects[4].occupied) && (rects[6].occupied == rects[4].occupied))
{
winner = rects[2].occupied;
}
}
if(winner != "_"){
trace("WINNER" + winner);
for (i = 0; i < 9; i++)
{
if (rects[i].hasEventListener(MouseEvent.CLICK))
{
rects[i].removeEventListener(MouseEvent.CLICK,moveNextTurn)
}
}
var tf:TextField = addChild(new TextField()) as TextField;
tf.defaultTextFormat = new TextFormat("", 20, 0xff0000);
tf.text = winner + " wins";
tf.x = 200;
tf.y = 200;
}
if (currentMove == 9 && winner == "_") {
trace("DRAW REEPLAy");
//TODO: replay logic
}
}
}
}
import flash.display.Graphics;
import flash.display.Sprite;
class Rect extends Sprite {
public var id:Number;
public var occupied:String = "_";// should be 0/_/X
function Rect() {
var g:Graphics = this.graphics;
g.lineStyle(1, 0x00ff00);
g.beginFill(0x000000);
g.drawRect(0, 0, 50, 50);
}
}
class Circle extends Sprite {
function Circle() {
var g:Graphics = this.graphics;
g.lineStyle(5, 0xff0000);
g.drawCircle(10, 10, 10);
}
}
class Cross extends Sprite {
function Cross() {
var g:Graphics = this.graphics;
g.lineStyle(5, 0x0000ff);
g.moveTo(0, 0);
g.lineTo(20, 20);
g.moveTo(20, 0);
g.lineTo(0, 20);
}
}
its a working example you can compile it, no need of graphics, hope it help