Print WebView with multiple pages in Xamarin UWP - printing

I am trying to print web page in xamarin forms. I am using DependencyService to print webview, which I have implemented in android successfully.
For Windows UWP,
I referred to this link:
https://forums.xamarin.com/discussion/91163/problem-with-printing-webview-in-uwp-phone
The approach used in this is printing only the first page of the webpage.
Edit :
I created an interface IPrint providing only the html source to the function.
public interface IPrint
{
void PrintAsync(string htmlSource);
}
In PrintAsync function (in Windows UWP project),
async void IPrint.PrintAsync(string htmlSource)
{
ViewToPrint.NavigateToString(htmlSource);
ViewToPrint.LoadCompleted += ViewToPrint_LoadCompleteAsync;
}
When WebView is completely loaded,
private async void ViewToPrint_LoadCompleteAsync(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
if (PrintDoc != null)
{
printDoc.AddPages -= PrintDoc_AddPages;
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
}
this.printDoc = new PrintDocument();
try
{
printDoc.AddPages += PrintDoc_AddPages;
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
PrintDoc = null;
GC.Collect();
}
To add pages in PrintDocument,
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
To implement multiple pages printing,
I referred this link : https://stackoverflow.com/a/17222629/6366591
I changed AddPages function to the following, but it doesn't seem to work for me.
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
rectangleList = GetWebPages(ViewToPrint, new Windows.Foundation.Size(100d, 150d));
foreach (Windows.UI.Xaml.Shapes.Rectangle rectangle in rectangleList)
{
printDoc.AddPage(rectangle);
}
printDoc.AddPagesComplete();
}
You can find GetWebPages() function here.
List<Windows.UI.Xaml.Shapes.Rectangle> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded += (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
WebViewBrush GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}

#Jerry Nixon's method worked well on my side. Since his code sample was posted on that thread about five years ago. For current UWP APIs, I just done a little changes(e.g, webView.InvokeScriptAsync). I also saw that you call the webView.InvokeScriptAsync method in your code. That's good. But you call the GetResults() method, I did not suggest you call GetResults() method. Because invoking javascript code sometimes will take you a lot of time. You might get the exception A method was called at an unexpected time.
Then, I also noticed that your printing flow is a bit of a mess. Please read Print from your app to learn the standardized printing process.
You could check the official code sample Printing sample for details.
The following was the updated code of your code snippet:
async Task<List<Windows.UI.Xaml.Shapes.Rectangle>> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded +=async (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = await GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
async Task<WebViewBrush> GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}
I used the Printing sample and put my above updated code in it and do some relevant changes, then I could print all web pages successfully.

Related

for embedded PDFs, can PDFJS support both scrolling and jump to a page number at the same time?

This seems like it should be very standard behavior.
I can display a scrollable PDF with:
var container = document.getElementById('viewerContainer');
var pdfViewer = new PDFJS.PDFViewer({
container: container,
});
PDFJS.getDocument(DEFAULT_URL).then(function (pdfDocument) {
pdfViewer.setDocument(pdfDocument);
});
and I can display the PDF page by page with something like:
PDFJS.getDocument(URL_ANNOTATED_PDF_EXAMPLE).then(function getPdfHelloWorld(pdf) {
pdf.getPage(pageNumber).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
But can't seem to find any reference in the API to both allow scrolling and jumping to a particular page, besides:
pdfViewer.currentPageNumber = 3;
which doesn't work...
So I found a way to make this work (mixed with a little Angular code, "$scope.$watch...") I now have other problems with font decoding. But here is a solution that might help someone else.
var me = this;
PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK;
var container = document.getElementById('capso-court-document__container');
function renderPDF(url, container) {
function renderPage(page) {
var SCALE = 1;
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: page.pageIndex + 1,
scale: SCALE,
defaultViewport: page.getViewport(SCALE),
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
annotationLayerFactory: new PDFJS.DefaultAnnotationLayerFactory()
});
pdfPageView.setPdfPage(page);
return pdfPageView.draw();
}
function renderPages(pdfDoc) {
var pageLoadPromises = [];
for (var num = 1; num <= pdfDoc.numPages; num++) {
pageLoadPromises.push(pdfDoc.getPage(num).then(renderPage));
}
return $q.all(pageLoadPromises);
}
PDFJS.disableWorker = true;
return PDFJS.getDocument(url)
.then(renderPages);
}
$scope.$watch(function() {
return {
filingUrl: me.filingUrl,
whenPageSelected: me.whenPageSelected,
};
}, function(newVal, oldVal) {
if (newVal.filingUrl) {
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED;
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED_2;
//newVal.filingUrl = URL_EXAMPLE_PDF_MULTI_PAGE;
if (newVal.filingUrl !== oldVal.filingUrl &&
newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
//HACK - create new container for each newly displayed PDF
container.innerHTML = '';
var newContainerForNewPdfSelection = document.createElement('div');
container.appendChild(newContainerForNewPdfSelection);
renderPDF(newVal.filingUrl, newContainerForNewPdfSelection).then(function() {
if (newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
});
}
}, true);
function scrollToPage(pageNumber) {
var pageContainer = document.getElementById('pageContainer' + pageNumber);
if (pageContainer) {
container.scrollTop = pageContainer.offsetTop;
} else {
console.warn('pdf pageContainer doesn\'t exist for index', pageNumber);
}
}

Printing from Win RT Application (Windows 8.1 App)

I am developing a POS application in windows 8.1 (Universal App).
Order receipt will be printed from the application and even I am able to do so.
Printer - EPSON TM-U220D
Input - A grid is being created pragmatically with dynamic content within the ViewModel. So this grid is the input for printer
Output - In the print preview (Attahced pic 1) all looks good but when the receipt is actually printed then content is cut off from the end (Attahced pic 2)
PIC 1
PIC 2
Observations -
If I print a normal text file manually using print command (Right click file and then print), then all content is printed perfectly.
If I print that SAME content, from the application, by creating Dynamic grid, then with Small font size print is good but with bit bigger font size content again cuts off.
Tried -
Optimized the code for Creating Gird, by specifying height
Questions-
If preview is all good then why not output
Did anyone tried using ePOS-Print_SDK_141020E for Windows Store app?
Generate Dynamic Grid Code
private void AddRows(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
RowDefinition row = new RowDefinition();
row.Height = GridLength.Auto;
grid.RowDefinitions.Add(row);
}
}
private void AddColumns(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition());
}
}
private TextBlock CreateTextBlock(string text, Color color, FontWeight fw, double fs = 10, int thick = 5)
{
if (color == null) color = Colors.Black;
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = text;
txtBlock1.FontSize = fs;
txtBlock1.FontWeight = fw;
txtBlock1.Foreground = new SolidColorBrush(color);
txtBlock1.VerticalAlignment = VerticalAlignment.Center;
txtBlock1.Margin = new Thickness(thick);
return txtBlock1;
}
private async Task<Grid> CreateDynamicWPFGrid()
{
Grid ParentGrid = new Grid();
AddRows(ParentGrid, 8);
/* Start First Grid*/
Grid DynamicGrid = new Grid();
DynamicGrid.Width = 230;
DynamicGrid.HorizontalAlignment = HorizontalAlignment.Left;
DynamicGrid.VerticalAlignment = VerticalAlignment.Top;
DynamicGrid.Margin = new Thickness(24, 0, 0, 0);
AddColumns(DynamicGrid, 2);
AddRows(DynamicGrid, 3);
TextBlock txtBlock1 = CreateTextBlock(DateTime.Now.ToString("M/d/yy"), Colors.Black, FontWeights.Normal);
Grid.SetRow(txtBlock1, 0);
Grid.SetColumn(txtBlock1, 1);
.
.
.
.
Return ParentGrid;
}
Printer Events Code
//Register Print Contract
async Task RegisterPrintContract()
{
PrintManager manager = PrintManager.GetForCurrentView();
manager.PrintTaskRequested += OnPrintTaskRequested;
await PrintManager.ShowPrintUIAsync();
}
//Unregister Print Contract
void UnregisterPrintContract()
{
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= OnPrintTaskRequested;
}
void OnPrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
// If I need to be asynchronous, I can get a deferral. I don't *need*
// to do this here, I'm just faking it.
var deferral = args.Request.GetDeferral();
PrintTask printTask = args.Request.CreatePrintTask("My Print Job", OnPrintTaskSourceRequestedHandler);
printTask.Completed += OnPrintTaskCompleted;
deferral.Complete();
}
void OnPrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
{
// TODO: Tidy up.
this._document = null;
this._pages = null;
}
async void OnPrintTaskSourceRequestedHandler(PrintTaskSourceRequestedArgs args)
{
var deferral = args.GetDeferral();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
this._document = new PrintDocument();
this._document.Paginate += OnPaginate;
this._document.GetPreviewPage += OnGetPreviewPage;
this._document.AddPages += OnAddPages;
// Tell the caller about it.
args.SetSource(this._document.DocumentSource);
});
deferral.Complete();
}
void OnAddPages(object sender, AddPagesEventArgs e)
{
// Loop over all of the preview pages and add each one to add each page to be printied
// We should have all pages ready at this point...
foreach (var page in this._pages)
{
//this._pages[page.Key]
this._document.AddPage(this._pages[page.Key]);
}
PrintDocument printDoc = (PrintDocument)sender;
// Indicate that all of the print pages have been provided
printDoc.AddPagesComplete();
}
async void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
Grid x = await CreateDynamicWPFGrid();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// NB: assuming it's ok to keep all these pages in
// memory. might not be the right thing to do
// of course.
if (this._pages == null)
{
this._pages = new Dictionary<int, UIElement>();
}
if (!this._pages.ContainsKey(e.PageNumber))
{
this._pages[e.PageNumber] = x;
}
if (this._document == null)
this._document = new PrintDocument();
this._document.SetPreviewPage(e.PageNumber, this._pages[e.PageNumber]);
}
);
}
async void OnPaginate(object sender, PaginateEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// I have one page and that's *FINAL* !
this._document.SetPreviewPageCount(e.CurrentPreviewPageNumber, PreviewPageCountType.Final);
});
}

Change colors in devexpress charts

I am drawing a pie chart using Devexpress in my MVC project.
While doing it by default my chart generated with three colors, as below
but my client is not satisfied, with the colors of it and wanted me to change them which match with our application background, so please help me, how to do this.
Thanks in advance.
Here is my code.
settings.Name = "chart";
settings.Width = 600;
settings.Height = 250;
settings.BorderOptions.Visible = false;
Series series1 = new Series("Type", DevExpress.XtraCharts.ViewType.Pie3D);
settings.Series.Add(series1);
series1.ArgumentScaleType = ScaleType.Qualitative;
series1.ArgumentDataMember = "ClassName";
series1.ValueScaleType = ScaleType.Numerical;
series1.ValueDataMembers.AddRange(new string[] { "PercentageValues" });
series1.LegendPointOptions.PointView = PointView.ArgumentAndValues;
series1.LegendPointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
series1.LegendPointOptions.ValueNumericOptions.Precision = 0;
series1.Label.ResolveOverlappingMode = ResolveOverlappingMode.Default;
series1.Label.Visible = false;
Please refer the following code. I have successfully implemented the same for giving custom color for rangebar. I guess it will work for your case also
settings.CustomDrawSeriesPoint = (s, ev) =>
{
BarDrawOptions drawOptions = ev.SeriesDrawOptions as BarDrawOptions;
if (drawOptions == null)
return;
Color colorInTarget = Color.Blue;
double x = ev.SeriesPoint.Values[0];
double y = ev.SeriesPoint.Values[1];
if (x == 0)
{ //Do starting
colorInTarget = Color.FromArgb(159,125, 189);
}
else{
//Red - price Increase
// Green price Decrease
if (y > previousYValue)
{
colorInTarget = Color.Red; ;
}
else
{
colorInTarget = Color.Green;
}
}
previousYValue = y;
drawOptions.Color = colorInTarget;
drawOptions.FillStyle.FillMode = FillMode.Solid;
drawOptions.Border.Color = Color.Transparent;
};
you can set the theme and palette properties of the chart control. follow the links below to devexpress documentation. although the examples refers to winform application they are still avaliable in asp.net mvc controls.
http://documentation.devexpress.com/#WindowsForms/CustomDocument7433
http://documentation.devexpress.com/#WindowsForms/CustomDocument5538
// Define the chart's appearance and palette.
barChart.AppearanceName = "Dark";
barChart.PaletteName = "Opulent";
private List<StudentClass.ChartsPointsSummary> GetStudentSummaryResults()
{
var StudentId = Convert.ToInt32(Request.Params["StudentID"]);
var StudentDetailsP = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var Presents = StudentDetailsP.Select(p => new { p.Months, p.Presents});
var CountsP = StudentDetailsP.Count();
List<StudentClass.ChartsPointsSummary> MT = new List<StudentClass.ChartsPointsSummary>();
foreach (var ab in Presents)
{
MT.Add(new StudentClass.ChartsPointsSummary { PresentSummaryX = ab.Months, PresentSummaryY = Convert.ToInt32(ab.Presents) });
}
var StudentDetailsA = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var Absents = StudentDetailsP.Select(p => new { p.Months, p.Absents });
var CountsA = StudentDetailsA.Count();
foreach (var ab in Absents)
{
MT.Add(new StudentClass.ChartsPointsSummary { AbsentSummaryX = ab.Months, AbsentSummaryY = Convert.ToInt32(ab.Absents) });
}
var StudentDetailsL = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var CountL = StudentDetailsL.Count();
var Leaves = StudentDetailsP.Select(p => new { p.Months, p.Leaves });
foreach (var ab in Leaves)
{
MT.Add(new StudentClass.ChartsPointsSummary { LeaveSummaryX = ab.Months, LeaveSummaryY = Convert.ToInt32(ab.Leaves) });
}
return MT;
}
#Html.DevExpress().Chart(settings =>
{
settings.Name = "SummaryDetailsById";
settings.Width = 1032;
settings.Height = 250;
Series chartSeries = new Series("Presents", DevExpress.XtraCharts.ViewType.Bar);
chartSeries.ArgumentDataMember = "PresentSummaryX";
chartSeries.ValueDataMembers[0] = "PresentSummaryY";
settings.Series.Add(chartSeries);
Series chartSeries2 = new Series("Absents", DevExpress.XtraCharts.ViewType.Bar);
chartSeries2.ArgumentDataMember = "AbsentSummaryX";
chartSeries2.ValueDataMembers[0] = "AbsentSummaryY";
settings.Series.Add(chartSeries2);
Series chartSeries3 = new Series("Leaves", DevExpress.XtraCharts.ViewType.Bar);
chartSeries3.ArgumentDataMember = "LeaveSummaryX";
chartSeries3.ValueDataMembers[0] = "LeaveSummaryY";
settings.Series.Add(chartSeries3);
settings.CrosshairEnabled = DefaultBoolean.Default;
settings.BackColor = System.Drawing.Color.Transparent;
settings.BorderOptions.Visibility = DefaultBoolean.True;
settings.Titles.Add(new ChartTitle()
{
Text = "Student Attendance Summary"
});
XYDiagram diagram = ((XYDiagram)settings.Diagram);
diagram.AxisX.Label.Angle = -30;
diagram.AxisY.Interlaced = true;
}).Bind(Model).GetHtml()

AS2 TweenLite: tween to frame

I have the following setup loaded:
import com.greensock.*;
import com.greensock.easing.*;
import com.greensock.plugins.*;
TweenPlugin.activate([FramePlugin]);
OverwriteManager.init(OverwriteManager.AUTO);
and am using the following code to tween an mc to frame 20.
TweenLite.to(circle, 1, {frame:20, ease:Elastic.easeOut});
Problem is nothing happens, circle is a variable containing my mc and traces fine.
Output of
trace(circle); = _level0.circle
Can anyone see why this isn't working? The MC contains a shapetween.
Edit:
Ok so I have tested it in a new fla with the same MC and it isn't the MC that is the problem it has to do with some other part of my code preventing it.
Here is my entire code... can anyone see anything that would stop the tween to frame working? If I remove for (MovieClip in txts) {
txts[MovieClip]._alpha = 0;
} and put the tween above it it works, but as soon as it is inside a rollover again it doesn't.
Entire code:
import com.greensock.*;
import com.greensock.easing.*;
import com.greensock.plugins.*;
TweenPlugin.activate([ColorTransformPlugin, FramePlugin]);
OverwriteManager.init(OverwriteManager.AUTO);
var angle:Number = 0;
var originX:Number = Stage.width/2;
var originY:Number = Stage.height/2;
var radiusX:Number = 320.5;
var radiusY:Number = 247.5;
var steps:Number = 360;
var speed:Number = 0.4/steps;
var circle:MovieClip = this.circle;
var circleTxt:MovieClip = this.circle.titleTxt;
var squareHeight:Number = 340.2;
var buttons:Array = new Array(this.faith, this.social, this.ability, this.age, this.orientation, this.ethnicity, this.sex);
var txts:Array = new Array("faithTxt", "socialTxt", "abilityTxt", "ageTxt", "orientationTxt", "ethnicityTxt", "sexTxt");
var tweens:Array = new Array();
for (MovieClip in txts) {
txts[MovieClip]._alpha = 0;
}
for (i=0; i<buttons.length; i++) {
buttons[i].onRollOver = function() {
var current:MovieClip = this;
circle.onEnterFrame = function() {
if (this._currentframe == 20) {
delete this.onEnterFrame;
delete circleTxt.onEnterFrame;
current.txt._alpha = 100;
}
};
noScale(circleTxt);
txtName = current._name+"Txt";
current.txt = this._parent.attachMovie(txtName, txtName, this._parent.getNextHighestDepth());
current.txt._alpha = 0;
circle.txtHeight = circle.active.txt._height/2+40;
var oppX:Number = Stage.width-this._x;
var oppY:Number = Stage.height-this._y;
if (oppX-227.8<=20) {
var difference:Number = Math.abs(20-(oppX-227.8));
oppX += difference;
} else if (oppX+227.8>=Stage.width-20) {
var difference:Number = Math.abs(780-(oppX+227.8));
oppX -= difference;
}
if (oppY-172.1<=20) {
var difference:Number = Math.abs(20-(oppY-172.1));
oppY += difference;
} else if (oppY+172.1>=580) {
var difference:Number = Math.abs(580-(oppY+172.1));
oppY -= difference;
}
circle.active.txt._x = oppX;
circle.active.txt._y = oppY;
TweenLite.to(circle,1,{frame:20});
TweenLite.to(circle,0.5,{_height:circle.txtHeight});
TweenLite.to(circle,1,{_x:oppX, _y:oppY, ease:Quint.easeInOut});
TweenLite.to(circleTxt,1,{_alpha:0});
TweenLite.to(this,0.5,{colorTransform:{tint:0x99ff00, tintAmount:0.5}});
for (MovieClip in buttons) {
delete buttons[MovieClip].onEnterFrame;
if (buttons[MovieClip] != this) {
TweenLite.to(buttons[MovieClip],0.5,{colorTransform:{tint:0xffffff, tintAmount:0.9}});
TweenLite.to(buttons[MovieClip]._line,0.5,{colorTransform:{tint:0xffffff, tintAmount:0.9}});
}
}
};
buttons[i].onRollOut = function() {
removeMovieClip(this.txt);
circle.onEnterFrame = function() {
if (this._currentframe == 1) {
delete this.onEnterFrame;
delete circleTxt.onEnterFrame;
}
};
noScale(circleTxt);
TweenLite.to(circle,0.2,{_height:173});
TweenLite.to(circle,0.5,{_x:Stage.width/2, _y:Stage.height/2});
TweenLite.to(circleTxt,1,{_alpha:100});
for (MovieClip in buttons) {
buttons[MovieClip].onEnterFrame = function() {
moveButtons(this);
controlButtons(this);
};
TweenLite.to(buttons[MovieClip],0.5,{colorTransform:{tint:null, tintAmount:0}});
TweenLite.to(buttons[MovieClip]._line,0.5,{colorTransform:{tint:null, tintAmount:0}});
}
};
buttons[i].onEnterFrame = function() {
moveButtons(this);
controlButtons(this);
};
buttons[i]._order = (360/buttons.length)*1000+(i+1);
buttons[i]._linedepth = buttons[i].getDepth()-1000;
}
function noScale(mc) {
mc.onEnterFrame = function() {
this._yscale = 10000/this._parent._yscale;
};
}
function moveButtons(e) {
var lineName:String = new String(e._name+"line");
var lineMC:MovieClip = createEmptyMovieClip(lineName, e._linedepth);
with (lineMC) {
beginFill();
lineStyle(2,0x000000,100);
moveTo(e._x,e._y);
lineTo(Stage.width/2,Stage.height/2);
endFill();
}
e.rotation = Math.atan2(e._y-Stage.height/2, e._x-Stage.width/2);
e._line.dist = Math.sqrt(Math.abs(e._x-Stage.width/2) ^ 2+Math.abs(e._y-Stage.height/2) ^ 2);
e._line = lineMC;
e._anglePhase = (angle+e._order)/Math.PI*2.8;
e._x = originX+Math.sin(e._anglePhase)*radiusX;
e._y = originY+Math.cos(e._anglePhase)*radiusY;
}
function controlButtons(e) {
angle += speed;
if (angle>=360) {
angle -= 360;
}
}
Heh Solved, for some reason it doesn't like for (MovieClip in Array){} anywhere in your code, so if I substitute that for for (a in Array){} it seems to work. Odd.

AS2: don't perform rollout until motion finished

I have an mc with some tweens applied to it, but if you roll out before they are done they break. I don't want to disable the button while tweens are running because if you roll out while they run you confuse the user because nothing happens and you get stuck in that frame.
What I want is to acknowledge the rollout during the tween (or after) but not run until the tweens are finished. I cannot seem to access the onmotionfinished of the tween in the rollover function from the rollout function however.
Any ideas?
If it helps here is my rollover:
buttons[i].onRollOver = function() {
var oppX:Number = Stage.width-this._x;
var oppY:Number = Stage.height-this._y;
if (oppX-209.8<=20) {
var difference:Number = Math.abs(20-(oppX-209.8));
oppX += difference;
} else if (oppX+209.8>=780) {
var difference:Number = Math.abs(780-(oppX+209.8));
oppX -= difference;
}
if (oppY-172.1<=20) {
var difference:Number = Math.abs(20-(oppY-172.1));
oppY += difference;
} else if (oppY+172.1>=580) {
var difference:Number = Math.abs(580-(oppY+172.1));
oppY -= difference;
}
var TweenX:Tween = new Tween(circle, "_x", mx.transitions.easing.Strong.easeOut, circle._x, oppX, 1, true);
var TweenY:Tween = new Tween(circle, "_y", mx.transitions.easing.Strong.easeOut, circle._y, oppY, 1, true);
circle.gotoAndPlay("out");
myColor = new Color(this);
myColor.setTint(153,255,0,30);
for (MovieClip in buttons) {
delete buttons[MovieClip].onEnterFrame;
if (buttons[MovieClip] != this) {
buttons[MovieClip].enabled = false;
myColor = new Color(buttons[MovieClip]);
myColor.setTint(255,255,255,80);
myColor = new Color(buttons[MovieClip]._line);
myColor.setTint(255,255,255,80);
}
}
};
and my rollOut:
buttons[i].onRollOut = function() {
this.onMotionComplete = function() {
var TweenX:Tween = new Tween(circle, "_x", mx.transitions.easing.Strong.easeOut, circle._x, 400, 0.5, true);
var TweenY:Tween = new Tween(circle, "_y", mx.transitions.easing.Strong.easeOut, circle._y, 300, 0.5, true);
TweenY.onMotionFinished = function() {
for (MovieClip in buttons) {
buttons[MovieClip].enabled = true;
}
};
this._parent.circle.gotoAndPlay("in");
for (MovieClip in buttons) {
buttons[MovieClip].onEnterFrame = function() {
moveButtons(this);
controlButtons(this);
};
myColor = new Color(buttons[MovieClip]);
myColor.setTint(255,255,255,0);
}
};
Realised that it wasn't the tween causing most of the problems that it was the gotoandplay because i had my stop(); calls on the same frame as the markers on that movieclip causing them to get stuck.
Did have some trouble with tween (the rollout jumped back to the rollover position if its tweens were called mid tween) but I decided to push the tweens to an array making them globally accessible and purge the array onmotionfinished then in the rollout check to see if the array contains anything and if so kill off the old tweens first.
Final product:
buttons[i].onRollOver = function() {
circle.active = this;
var oppX:Number = Stage.width-this._x;
var oppY:Number = Stage.height-this._y;
if (oppX-209.8<=20) {
var difference:Number = Math.abs(20-(oppX-209.8));
oppX += difference;
} else if (oppX+209.8>=780) {
var difference:Number = Math.abs(780-(oppX+209.8));
oppX -= difference;
}
if (oppY-172.1<=20) {
var difference:Number = Math.abs(20-(oppY-172.1));
oppY += difference;
} else if (oppY+172.1>=580) {
var difference:Number = Math.abs(580-(oppY+172.1));
oppY -= difference;
}
var TweenX:Tween = new Tween(circle, "_x", mx.transitions.easing.Strong.easeOut, circle._x, oppX, 1, true);
var TweenY:Tween = new Tween(circle, "_y", mx.transitions.easing.Strong.easeOut, circle._y, oppY, 1, true);
TweenY.onMotionFinished = function () {
tweens.length = 0;
}
tweens.push(TweenX,TweenY);
circle.gotoAndPlay("out");
myColor = new Color(this);
myColor.setTint(153,255,0,30);
for (MovieClip in buttons) {
delete buttons[MovieClip].onEnterFrame;
if (buttons[MovieClip] != this) {
buttons[MovieClip].enabled = false;
myColor = new Color(buttons[MovieClip]);
myColor.setTint(255,255,255,80);
myColor = new Color(buttons[MovieClip]._line);
myColor.setTint(255,255,255,80);
}
}
};
buttons[i].onRollOut = function() {
if (tweens.length != 0) {
tweens[0].stop();
tweens[1].stop();
delete tweens[0];
delete tweens[1];
tweens.length = 0;
}
circle.gotoAndPlay("in");
var TweenX:Tween = new Tween(circle, "_x", mx.transitions.easing.Strong.easeOut, circle._x, 400, 0.5, true);
var TweenY:Tween = new Tween(circle, "_y", mx.transitions.easing.Strong.easeOut, circle._y, 300, 0.5, true);
TweenY.onMotionFinished = function() {
circle._x = 400;
circle._y = 300;
for (MovieClip in buttons) {
buttons[MovieClip].enabled = true;
}
};
for (MovieClip in buttons) {
buttons[MovieClip].onEnterFrame = function() {
moveButtons(this);
controlButtons(this);
};
myColor = new Color(buttons[MovieClip]);
myColor.setTint(255,255,255,0);
}
};

Resources