Overlap Stacked Area Chart in WinForms - winforms

I am trying to overlap a stacked area chart on an existing chart in a WinForm application (using System.Windows.Forms.DataVisualization.Charting library).
As per the above screenshot, the green colored stacked area chart should be at the highlighted (yellow) color line. However, currently the code creates it on top of the existing stacked area chart (blue).
How can I change it such that the blue and green color charts overlap?
Code:
private void DrawChart()
{
var dataTable = new DataTable();
dataTable.Columns.Add("Year");
dataTable.Columns.Add("2020");
dataTable.Columns.Add("2021");
dataTable.Columns.Add("2022");
dataTable.Columns.Add("2023");
dataTable.Columns.Add("2024");
var dr = dataTable.NewRow();
dr = dataTable.NewRow();
dr["Year"] = "Stacked Area 1";
dr["2020"] = 20000;
dr["2021"] = 60000;
dr["2022"] = 130000;
dr["2023"] = 190000;
dr["2024"] = 220000;
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr["Year"] = "Stacked Area 2";
dr["2020"] = 30000;
dr["2021"] = 70000;
dr["2022"] = 140000;
dr["2023"] = 200000;
dr["2024"] = 230000;
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr["Year"] = "Overlapping Stacked Area 1";
dr["2020"] = 10000;
dr["2021"] = 50000;
dr["2022"] = 120000;
dr["2023"] = 180000;
dr["2024"] = 210000;
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr["Year"] = "Overlapping Stacked Area 2";
dr["2020"] = 15000;
dr["2021"] = 60000;
dr["2022"] = 130000;
dr["2023"] = 190000;
dr["2024"] = 220000;
dataTable.Rows.Add(dr);
chart.ChartAreas["Default"].AxisX.Crossing = 0;
chart.ChartAreas["Default"].AxisY.Crossing = 0;
chart.Visible = true;
foreach (DataRow row in dataTable.Rows)
{
string seriesName = row["Year"].ToString();
if (chart.Series.FindByName(seriesName) == null)
{
chart.Series.Add(seriesName);
switch (seriesName)
{
case "Stacked Area 1":
chart.Series[seriesName].ChartType = SeriesChartType.StackedArea;
chart.Series[seriesName].Color = Color.Transparent;
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.Black;
break;
case "Stacked Area 2":
chart.Series[seriesName].ChartType = SeriesChartType.StackedArea;
chart.Series[seriesName].Color = Color.LightBlue;
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.Black;
break;
case "Overlapping Stacked Area 1":
chart.Series[seriesName].ChartType = SeriesChartType.StackedArea;
chart.Series[seriesName].SetDefault(true);
chart.Series[seriesName].Color = Color.Transparent;
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.FromArgb(100, Color.Green);
break;
case "Overlapping Stacked Area 2":
chart.Series[seriesName].ChartType = SeriesChartType.StackedArea;
chart.Series[seriesName].SetDefault(true);
chart.Series[seriesName].Color = Color.FromArgb(100, Color.Green);
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.FromArgb(100, Color.Green);
break;
}
}
chart.Series[seriesName].Points.Clear();
var years = dataTable.Columns.Count;
for (int i = 1; i < years; i++)
{
string columnName = dataTable.Columns[i].ColumnName;
if (row[columnName] != null && !String.IsNullOrEmpty(row[columnName].ToString()))
{
var val = Convert.ToInt64(row[columnName].ToString());
chart.Series[seriesName].Points.AddXY(columnName, val);
}
}
}
}

There are a number of ways to solve this, but I'd say that the best place to start would be changing the type of Series from stacked to "Range". If you look into that series type it definitely seems to be what you're looking for. I've created some example code adapted from your original code. I've used tuples because I didn't want to spend a massive amount of time doing this, but I definitely wouldn't recommend using them for this.
private void DrawChart()
{
var dataTable = new DataTable();
dataTable.Columns.Add("Year");
dataTable.Columns.Add("2020",typeof(Tuple<int,int>));
dataTable.Columns.Add("2021",typeof(Tuple<int,int>));
dataTable.Columns.Add("2022",typeof(Tuple<int,int>));
dataTable.Columns.Add("2023",typeof(Tuple<int,int>));
dataTable.Columns.Add("2024", typeof(Tuple<int, int>));
var dr = dataTable.NewRow();
dr = dataTable.NewRow();
dr["Year"] = "Range 1";
dr["2020"] = new Tuple<int,int>(20000, 30000);
dr["2021"] = new Tuple<int,int>(60000, 70000);
dr["2022"] = new Tuple<int,int>(130000, 140000);
dr["2023"] = new Tuple<int,int>(190000, 200000);
dr["2024"] = new Tuple<int,int>(220000, 230000);
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr["Year"] = "Range 2";
dr["2020"] = new Tuple<int,int>(10000, 25000);
dr["2021"] = new Tuple<int,int>(50000, 90000);
dr["2022"] = new Tuple<int,int>(120000, 130000);
dr["2023"] = new Tuple<int,int>(180000, 210000);
dr["2024"] = new Tuple<int,int>(210000, 220000);
dataTable.Rows.Add(dr);
chart.ChartAreas["Default"].AxisX.Crossing = 0;
chart.ChartAreas["Default"].AxisY.Crossing = 0;
chart.Visible = true;
foreach (DataRow row in dataTable.Rows)
{
string seriesName = row["Year"].ToString();
Series series = null;
if (chart.Series.FindByName(seriesName) == null)
{
series = chart.Series.Add(seriesName);
switch (seriesName)
{
case "Range 1":
chart.Series[seriesName].ChartType = SeriesChartType.Range;
chart.Series[seriesName].Color = Color.FromArgb(100,Color.LightBlue);
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.Black;
break;
case "Range 2":
chart.Series[seriesName].ChartType = SeriesChartType.Range;
chart.Series[seriesName].SetDefault(true);
chart.Series[seriesName].Color = Color.FromArgb(100, Color.Green);
chart.Series[seriesName].BorderDashStyle = ChartDashStyle.Dot;
chart.Series[seriesName].BorderWidth = 2;
chart.Series[seriesName].BorderColor = Color.FromArgb(100, Color.Green);
break;
}
}
if (series == null) continue;
var years = dataTable.Columns.Count;
for (int i = 1; i < years; i++)
{
string columnName = dataTable.Columns[i].ColumnName;
if (row[columnName] != null && !String.IsNullOrEmpty(row[columnName].ToString()))
{
var val = (Tuple<int,int>) row[columnName];
series.Points.AddXY(columnName, val.Item1,val.Item2);
}
}
}
}

Related

Flash CS3 Deleting objects on stage

Ok so I have this minigame inside my main timeline. The minigame creates a bunch of objects dynamically inside an array using addChild(new a0), new a1, new a2 etc... Anyways at the end of the game, there's an option to either restart (resets scores and goes back to starting frame) or finished (goes back a few frames to the "main screen" which is on a different layer and back a few frames. If I choose either options, any of the objects that werent deleted from playing the game (getting a match) are left on the stage even when restarting or going back to the main frame. I've tried various methods of calling removeChild, setting arrays to empty and what not and I can't seem to figure out how to remove them. With the code that I will display here, I get this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at mousiesDay_fla::MainTimeline/clearGame()[mousiesDay_fla.MainTimeline::frame258:11]
at mousiesDay_fla::MainTimeline/tryAgain()[mousiesDay_fla.MainTimeline::frame258:29]
Here is the code
stop();
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
function clearGame() {
for( var i:int = 0; i < numClips; i++ ) {
removeChild( myClip[i] );
}
myClip.length = 0;
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
}
function finished(evt:MouseEvent) {
clearGame();
gotoAndPlay(256);
}
function tryAgain(evt:MouseEvent) {
clearGame();
gotoAndPlay(257);
}
backBtn.addEventListener(MouseEvent.CLICK, goBack);
function goBack(evt:MouseEvent) {
gotoAndPlay(256);
}
import flash.utils.*;
var myTimer:Timer = new Timer(1000);
myTimer.addEventListener("timer", timedFunction);
myTimer.start();
function timedFunction(eventArgs:TimerEvent) {
var tc:int= 31 - myTimer.currentCount;
pTime.text = tc.toString();
if (myTimer.currentCount > 30) {
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
finBtn.visible = true;
finBtn.addEventListener(MouseEvent.CLICK, finished);
addChild(finBtn);
tryBtn.visible = true;
tryBtn.addEventListener(MouseEvent.CLICK, tryAgain);
addChild(tryBtn);
}
}
var mySound:Sound = new correctSound();
upgameScore = 0;
var numClips:Number = 7;
var myClip = new Array(numClips);
myClip[0] = addChild(new a0());
myClip[1] = addChild(new a1());
myClip[2] = addChild(new a2());
myClip[3] = addChild(new a3());
myClip[4] = addChild(new a4());
myClip[5] = addChild(new a5());
myClip[6] = addChild(new a6());
//myClip[7] = addChild(new a7());
//myClip[8] = addChild(new a8());
//myClip[9] = addChild(new a9());
myClip[0].name = "piece0";
myClip[1].name = "piece1";
myClip[2].name = "piece2";
myClip[3].name = "piece3";
myClip[4].name = "piece4";
myClip[5].name = "piece5";
myClip[6].name = "piece6";
//myClip[7].name = "piece7";
//myClip[8].name = "piece8";
//myClip[9].name = "piece9";
var nph = new Array(numClips);
nph[0] = nph0_mc;
nph[1] = nph1_mc;
nph[2] = nph2_mc;
nph[3] = nph3_mc;
nph[4] = nph4_mc;
nph[5] = nph5_mc;
nph[6] = nph6_mc;
//nph[7] = nph7_mc;
//nph[8] = nph8_mc;
//nph[9] = nph9_mc;
var tpg = new Array(numClips);
tpg[0] = tpg0_mc;
tpg[1] = tpg1_mc;
tpg[2] = tpg2_mc;
tpg[3] = tpg3_mc;
tpg[4] = tpg4_mc;
tpg[5] = tpg5_mc;
tpg[6] = tpg6_mc;
//tpg[7] = tpg7_mc;
//tpg[8] = tpg8_mc;
//tpg[9] = tpg9_mc;
var x0 = myClip[0].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y0 = myClip[0].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x1 = myClip[1].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y1 = myClip[1].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x2 = myClip[2].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y2 = myClip[2].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x3 = myClip[3].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y3 = myClip[3].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x4 = myClip[4].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y4 = myClip[4].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x5 = myClip[5].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y5 = myClip[5].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x6 = myClip[6].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y6 = myClip[6].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
/*var x7 = myClip[7].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y7 = myClip[7].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x8 = myClip[8].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y8 = myClip[8].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x9 = myClip[9].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y9 = myClip[9].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;*/
var j:Number;
for (var k:Number = 0; k < numClips; k++) {
myClip[k].addEventListener("mouseDown", pieceMove);
myClip[k].addEventListener("mouseUp", pieceMove);
}
function pieceMove(evt:Event):void {
if (evt.type == "mouseDown") {
//mySound.play();
evt.target.startDrag();
}
else if (evt.type == "mouseUp") {
//mySound.play();
evt.target.stopDrag();
for (j = 0; j < numClips; j++) {
if (evt.target.name == "piece" + j &&
evt.target.hitTestObject(nph[j]) == true) {
removeChild(myClip[j]);
nph[j].alpha = 0;
tpg[j].alpha = 100;
if (j == 2) {
setChildIndex(tpg[j], 1);
}
upgameScore++;
}
else if (evt.target.name == "piece" + j) {
evt.target.x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
evt.target.y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
}
}
scor.text = upgameScore.toString();
if (upgameScore == 10) {
msgbox.text = "Congratulations !";
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
}
}
}
I should mention that if you look near the end of the code where I do the testHitObject and then call removeChild after that, THAT particular delete works and removes the object from the frame.
Solved this one too. I should probably spend a bit more time before I post these.
As it turns out, when objects were being matched they were being removed as per the removeChild() function that was working. What I was doing then was iterating through the array and attempting to remove some objects that were already removed. So what i did was kept an array that matched the objects and when they were removed, changed a flag to 0. Then at the end, iterate through the new array and if there's a 1, remove the child object from the array with the same index. If there's a 0, ignore it. Now it works.

Scatterplot Not Showing

I'm doing an application that requires core plot for drawing charts, I'm new to this library and I am finding it pretty hard to find good documentation or examples. I'm running into a problem where the line for the graph is not being display despite the fact that the data source method is getting called and returning the right number at the right index. Also the x Axis is being displayed wrong (Check the image below(1.0)). The Y axis is set correctly and the increment is also correct. I've been playing around trying to figure out what it's wrong but I spent too much time already so I was hoping to find some one here that could help or point me at the right direction. This is my implementation file :
-(void)initPlot {
[self generateData];
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
- (void)generateData{
//Array containing all the dates that will be displayed on the X axis
dates = [NSArray arrayWithObjects:#"Apr 25", #"Apr 26", #"Apr 29",#"Apr 30", #"May 1", nil];
//Dictionary containing the name of the single set and its associated color
sets = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], #"Plot 1",nil];
_dataY = [[NSMutableArray alloc] init];
[_dataY insertObject:[NSNumber numberWithFloat:618.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:613.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:613.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:614.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:604.0] atIndex:0];
_dataForPlot = [[NSMutableArray alloc] init];
for(int i = 0; i < dates.count; i++){
NSString *date = [dates objectAtIndex:i];
NSNumber *price = [_dataY objectAtIndex:i];
NSMutableDictionary *point1 = [[[NSMutableDictionary alloc] initWithObjectsAndKeys:date, #"x", price, #"y", nil] autorelease];
[_dataForPlot addObject:point1];
}
NSLog(#"Data %#",_dataForPlot);
}
-(void)configureHost {
_hostView.allowPinchScaling = NO;
}
-(void)configureGraph {
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
_hostView.hostedGraph = graph;
graph.plotAreaFrame.masksToBorder = NO;
// Configure the Graph Padding
graph.paddingLeft = 0.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
graph.paddingBottom = 0.0f;
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
graph.plotAreaFrame.borderLineStyle = borderLineStyle;
graph.plotAreaFrame.paddingTop = 10.0;
graph.plotAreaFrame.paddingRight = 10.0;
graph.plotAreaFrame.paddingBottom = 40.0;
graph.plotAreaFrame.paddingLeft = 70.0;
// Set graph title
graph.title = #"Test";
// Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
graph.plotAreaFrame.borderLineStyle = nil;
}
- (void)configurePlots{
CPTColor *aColor = [CPTColor redColor];
CPTMutableLineStyle *barLineStyle = [[[CPTMutableLineStyle alloc] init] autorelease];
barLineStyle.lineWidth = 1.0;
barLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
// Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(5.0)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat([self lowerValue]) length:CPTDecimalFromFloat([self higherValue])];
dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = #"Plot 1";
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor :[CPTColor greenColor]
endingColor :[CPTColor blackColor]];
areaGradient.angle = -90.0f ;
CPTFill *areaGradientFill = [ CPTFill fillWithGradient :areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPTDecimalFromString (#"0.0");
dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationLinear;
// Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.4f)];
plotSpace.yRange = yRange;
// Create styles and symbols
CPTMutableLineStyle *aLineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
aLineStyle.lineWidth = 1.0;
aLineStyle.lineColor = aColor;
dataSourceLinePlot.dataLineStyle = aLineStyle;
//Add legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
theLegend.numberOfRows = sets.count;
theLegend.fill = [CPTFill fillWithColor:[CPTColor colorWithGenericGray:0.15]];
theLegend.borderLineStyle = barLineStyle;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15.0, 15.0);
whiteTextStyle.fontSize = 13.0;
theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 5.0;
theLegend.paddingLeft = 10.0;
theLegend.paddingTop = 10.0;
theLegend.paddingRight = 10.0;
theLegend.paddingBottom = 10.0;
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorTopLeft;
graph.legendDisplacement = CGPointMake(80.0, -10.0);
}
- (void)configureAxes{
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
// Line Style
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
//Axises
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
//Y axis
CPTXYAxis *y = axisSet.yAxis;
y.title = #"Price";
y.titleOffset = 50.0f;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
y. majorIntervalLength = CPTDecimalFromString(#"5");
y.minorTicksPerInterval = 4;
y.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
y.minorTickLineStyle = nil;
y.labelOffset = 2.0f;
// Configure x-axis
CPTXYAxis *x = axisSet.xAxis;
x. majorIntervalLength = CPTDecimalFromString (#"5");
x.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
x.majorIntervalLength = CPTDecimalFromInt(5);
x.minorTicksPerInterval = 0;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.majorGridLineStyle = majorGridLineStyle;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[_dataForPlot count]];
static CPTMutableTextStyle *labelTextStyle = nil;
labelTextStyle = [[CPTMutableTextStyle alloc] init];
labelTextStyle.color = [CPTColor whiteColor];
labelTextStyle.fontSize = 10.0f;
int index = 0;
for(NSString *date in dates){
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:date textStyle:labelTextStyle];
newLabel.tickLocation = CPTDecimalFromInt(index);
newLabel.offset = x.labelOffset + x.majorTickLength + 5;
newLabel.rotation = M_PI / 4;
[customLabels addObject:newLabel];
[newLabel release];
index++;
}
x.axisLabels = [NSSet setWithArray:customLabels];
}
- (float)higherValue{
NSNumber* max = [_dataY valueForKeyPath:#"#max.self"];
return [max floatValue];
}
- (float)lowerValue{
NSNumber* min = [_dataY valueForKeyPath:#"#min.self"];
return [min floatValue];
}
The Data Source Methods :
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return dates.count;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? #"x" : #"y");
NSNumber *num = 0;
//if ( [(NSString *)plot.identifier isEqualToString:#"Plot 1"] ) {
num = [[_dataForPlot objectAtIndex:index] valueForKey:key];
if ( fieldEnum == CPTScatterPlotFieldX ) {
num = 0;
}
//}
CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeInAnimation.duration = 1.0f;
fadeInAnimation.removedOnCompletion = NO;
fadeInAnimation.fillMode = kCAFillModeForwards;
fadeInAnimation.toValue = [NSNumber numberWithFloat:2.0];
[dataSourceLinePlot addAnimation:fadeInAnimation forKey:#"animateOpacity"];
NSLog(#"NUM : %# for key : %# at index : %i",num,key,index);
return num;
}
This is the image :
The x-axis is displayed exactly as you told it. It ranges between -0.25 and 5.25 (0 to 5 expanded by 10%) with five labels at 0, 1, 2, 3, and 4.
The datasource returns nil (0) for the CPTScatterPlotFieldX field for every point. This tells the plot to ignore that point. Based on the plot place range you've set up, you should return an NSNumber containing the index for that field.

Box2d Bounding Box Without Force

Currently, the Cocos2d-Box2d project is using a b2Vec2 to create a Bounding Box for the edge of the game. Because of this, the bounding Box isn't affecting kinematic bodies, which are bodies that aren't affected by force(meaning that the bodies will usually fly off the screen). I'm trying to see if there's a way to either make the kinematic body connect with the screen. If not, i would appreciate it if someone explain to me how I should make a boundingbox with static bodies around the corner of the screens.
Here is two ways...Try any one
// Method - 1
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0);
b2Body *mGroundBody ;
mGroundBody = self.world->CreateBody(&groundBodyDef);
NSString *strId = #"Ground Body";
mGroundBody->SetUserData(strId);
b2EdgeShape groundBox;
//bottom
groundBox.Set(b2Vec2(0.0f,0.0f), b2Vec2(mS.width/PTM_RATIO,0.0f));
mGroundBody->CreateFixture(&groundBox,0);
// top
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO, mS.height/PTM_RATIO));
mGroundBody->CreateFixture(&groundBox,0);
// left
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(0,0));
mGroundBody->CreateFixture(&groundBox,0);
// right
groundBox.Set(b2Vec2(mS.width/PTM_RATIO,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO,0));
mGroundBody->CreateFixture(&groundBox,0);
// Method - 2
//create 4 box2d walls...
float bW = (IS_IPAD) ? (8) : 2 ;
//top
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, (mS.height)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//bottom
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, 0);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//left
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(0, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//right
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width)/PTM_RATIO, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}

Adding columns and rows into a tablelayoutpanel row dynamically

Hi, I have a windows forms application written in c#. I use tablelayoutpanel that have 5 rows and a column. My question is how could we add red columns and row (they are shown in red color in the picture) into just row 3 in runtime/dynamically ? And how can we reach later to be able to add controls (labels, textboxes, buttons..) into them?
Thanks for advices..
Here an example :
private void GenerateControls()
{
TableLayoutPanel tableLayoutPanel1 = new TableLayoutPanel();
Button button1 = new Button();
Button button2 = new Button();
PictureBox pictureBox1 = new PictureBox();
TextBox textBox1 = new TextBox();
tableLayoutPanel1.SuspendLayout();
// tableLayoutPanel1
tableLayoutPanel1.ColumnCount = 2;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.Controls.Add(button2, 1, 0);
tableLayoutPanel1.Controls.Add(button1, 0, 0);
tableLayoutPanel1.Controls.Add(pictureBox1, 0, 1);
tableLayoutPanel1.Controls.Add(textBox1, 1, 1);
tableLayoutPanel1.Location = new System.Drawing.Point(12, 12);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 30F));
tableLayoutPanel1.Size = new System.Drawing.Size(388, 301);
tableLayoutPanel1.TabIndex = 0;
tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
// button1
button1.Dock = DockStyle.Fill;
button1.Location = new System.Drawing.Point(3, 3);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(188, 144);
button1.TabIndex = 0;
button1.Text = "button1";
button1.UseVisualStyleBackColor = true;
// button2
button2.Dock = DockStyle.Fill;
button2.Location = new System.Drawing.Point(197, 3);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(188, 144);
button2.TabIndex = 1;
button2.Text = "button2";
button2.UseVisualStyleBackColor = true;
// pictureBox1
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.Location = new System.Drawing.Point(3, 153);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new System.Drawing.Size(188, 145);
pictureBox1.TabIndex = 2;
pictureBox1.TabStop = false;
//pictureBox1.Image = Image.FromFile(#"C:\somepic.jpg");
// textBox1
textBox1.Dock = DockStyle.Fill;
textBox1.Location = new System.Drawing.Point(197, 153);
textBox1.Multiline = true;
textBox1.Name = "textBox1";
textBox1.Size = new System.Drawing.Size(188, 145);
textBox1.TabIndex = 3;
Controls.Add(tableLayoutPanel1);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
}
This void will manipulate borders
void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Column == 0)
{
var rectangle = e.CellBounds;
rectangle.Inflate(-1, -1);
ControlPaint.DrawBorder3D(e.Graphics, rectangle, Border3DStyle.Raised, Border3DSide.All); // 3D border
}
else if (e.Column == 1 && e.Row == 0)
{
var rectangle = e.CellBounds;
rectangle.Inflate(-1, -1);
ControlPaint.DrawBorder(e.Graphics, rectangle, Color.Red, ButtonBorderStyle.Dotted); // dotted border
}
}

Problem with image column in XtraTreeList

I use XtraTreeList control.
There are 2 columns: first for text and second for icon
Problem : I can't change default icon (zero index in corresponding imagelist). There are 3 images in imagelist.
For example I need to show icon which is located at 2 index
Code
TreeListColumn col = treeList1.Columns.Add();
col.Caption = "Text";
col.Visible = true;
TreeListColumn colImage = treeList1.Columns.Add();
colImage.Caption = "ImageColumn";
colImage.Visible = true;
RepositoryItemImageEdit imageEdit = new RepositoryItemImageEdit();
imageEdit.Images = imageList;
treeList1.RepositoryItems.Add(imageEdit);
colImage.ColumnEdit = imageEdit;
treeList1.BeginUnboundLoad();
TreeListNode node = treeList1.AppendNode(new object[] { "trololo", 2}, null);
node.SetValue(colImage.AbsoluteIndex, 2);
treeList1.EndUnboundLoad();
Thanks for everybody
Using RepositoryItemPictureEdit solved my problem. A little bit complex, but works
TreeListColumn col = treeList1.Columns.Add();
col.Caption = "Text";
col.Visible = true;
TreeListColumn colImage = treeList1.Columns.Add();
colImage.Caption = "ImageColumn";
colImage.Visible = true;
RepositoryItemPictureEdit imageEdit = new RepositoryItemPictureEdit();
imageEdit.ShowMenu = false;
treeList1.RepositoryItems.Add(imageEdit);
colImage.ColumnEdit = imageEdit;
treeList1.BeginUnboundLoad();
Image img = imageList.Images[1];
Bitmap bmp = new Bitmap(img);
TreeListNode node = treeList1.AppendNode(new object[] { "trololo", bmp }, null);
treeList1.EndUnboundLoad();
This task should be implemented using slightly different approach. First, you should use the RepositoryItemImageComboBox and populate its Items property. Each item has value and ImageIndex. The TreeList will show in a cell image from the item whose value equals the cell value. Here is the code which should work for you:
TreeListColumn col = treeList1.Columns.Add();
col.Caption = "Text";
col.Visible = true;
TreeListColumn colImage = treeList1.Columns.Add();
colImage.Caption = "ImageColumn";
colImage.Visible = true;
RepositoryItemImageComboBox imageEdit = new RepositoryItemImageComboBox();
imageEdit.SmallImages = imageList;
for(int i = 0; i < 3; i++)
imageEdit.Items.Add(new ImageComboBoxItem(i, i)); // i.e. value and image index
treeList1.RepositoryItems.Add(imageEdit);
colImage.ColumnEdit = imageEdit;
treeList1.BeginUnboundLoad();
TreeListNode node = treeList1.AppendNode(new object[] { "trololo", 2 }, null);
node.SetValue(colImage.AbsoluteIndex, 2);
treeList1.EndUnboundLoad();

Resources