i wan to delete a specific item from an array - actionscript-3

I have 9 mc in the stage [a,b,c.....i] , and this itemIndex[] content index of every mc , I want to delete a specific item from itemIndex[], but the problem I find is when I click to the same mc over and over the other items continue to delete from itemIndex[];
import flash.events.MouseEvent;
var myarray: Array = [a, b, c, d, e, f, g, h, i];
var itemIndex: Array = [];
for (var j: int = 0; j < myarray.length; j++) {
myarray[j].addEventListener(MouseEvent.CLICK, goto);
myarray[j].index = j;
itemIndex.push(j);
}
function goto(e: MouseEvent): void {
var r = e.target.index;
itemIndex.splice(e.target.index, 1);// for exemple wen i click to this movieClip with the name a
//the index of a is 0 ; but
trace(itemIndex);
}
//output = 1,2,3,4,5,6,7,8
// 1,2,3,4,5,6,7
// 1,2,3,4,5,6
// 1,2,3,4,5
// 1,2,3,4
// 1,2,3
// 1,2
// 1

Related

Finding matches from 2 ranges and replacing matches with a specific value, any way to optimize?

This is the sample sheet.
From this
1 Search area Bounty list Bullet
2 a i z a b c abc
3 e b d d e f def
4 y f h g h i ghi
5
6 1 2 3 4 5 6 7 8
7 Column #
To this
1 Search area Bounty list Bullet
2 abc ghi z a b c abc
3 def abc def d e f def
4 y def ghi g h i ghi
5
6 1 2 3 4 5 6 7 8
7 Column #
It will take a value "bounty" from the "bounty list" starting from (2,5) or "a", search around the "Search Area" in a sequence, from a, i, z, e, b, d, y, f, h. Then if it finds a cell or multiple cells that equals the value of "bounty", then it will place the value of "bullet" from column 8 on the current "bounty" row to those cells. The process will repeat in the sequence of a, b, c, d, e, f, g, h, i on the "bounty list". Both process moves to the left, and down.
function menuItem1()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var target = sheet.getDataRange().getValues();
for (var BountyRow = 2; BountyRow<target.length; BountyRow++)//switching rows in bounty list//
{
var bullet = sheet.getRange(BountyRow, 8).getValue(); //cell value to paste on targets//
for (var BountyColumn = 5; BountyColumn<8; BountyColumn++) //switching columns in bounty list//
{
var bounty = sheet.getRange(BountyRow, BountyColumn).getValue(); // cell value to search for//
if (bounty !=0)
{
for (var SearchRow = 1; SearchRow<target.length; SearchRow++) //switching row on search area//
{
for(var SearchColumn = 0; SearchColumn<4;SearchColumn++)//switching column on search area//
{
if(target[SearchRow][SearchColumn] == bounty) //if search target is found//
{
var found = target[SearchRow][SearchColumn];
sheet.getRange(SearchRow+1, SearchColumn+1).setValue(bullet);
Logger.log((found)+ " in "+"row"+(SearchRow+1)+", column"+(SearchColumn+1));
}
}
}
}
}
}
}
It involves thousands of searches which always use more than a minute and I was wondering if there is a more efficient way to do it?
In order to optimize your code you need to do two things:
Instead of using getValue() and setValue() for each cell (which makes you code slow)
retrieve all your bounty list and search are data once, with getValues()
assign the values to an array
replace matches within the the array
set the updated array values back into the range with setValues()
Make use of indexOf() and map()
to find matches and replace them more efficiently
Sample:
function menuItem1(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow=sheet.getLastRow();
var searchValues=sheet.getRange(2,1,lastRow-2+1,3).getValues();
var bountyValues=sheet.getRange(2,5,lastRow-2+1,3).getValues();
var bulletValues=sheet.getRange(2,8,lastRow-2+1,1).getValues();
for (var i = 0; i<bountyValues.length; i++){
for (var j = 0; j<bountyValues[0].length; j++){
if (bountyValues[i][j] !=0){
replaceValues(searchValues, bountyValues[i][j], bulletValues[i][0]);
}
}
}
sheet.getRange(2,1,lastRow-2+1,3).setValues(searchValues)
}
function replaceValues(search, bounty, bullet) {
for(var k=0;k<search.length;k++){
search[k]=search[k].map(function(search) {
var regex=new RegExp("\\b"+bounty+"\\b","g");
return search.toString().replace(regex, bullet);
});
}
}

Index Match Large Array Google Script Taking Very Long

I have the function below where I am trying to scrape 4 websites, and then combine the results into a spreadsheet. Is there a faster way to match over a large array that isn't the INDEX/MATCH formulas. My desired output would be (obv this is an example)
MLBID | FG_ID | PA | K | K% | wOBA
12345 | 12345 | 12 | 5 | 41.7% | .300
While the code I have below works, it takes wayyyy too long reaches the 6-minute limit of Google Script. The matching that I am trying to do is with ~4000 rows. I have commented my code as much as possible.
function minors_batting_stats() {
//this is the spreadsheet where I have a list of all of the IDs -- MLB and FG
var ids = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Player List");
//this is the output sheet
var mb18vR_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2018 minors bat vs R");
//various URLs I am trying to scrape
var mb18vR_PA_url = 'https://www.mlb.com/prospects/stats/search?level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=results&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
var mb18vR_SO_url = 'https://www.mlb.com/prospects/stats/search?pa_result=strikeout&level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=results&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
var mb18vR_wOBA_url = 'https://www.mlb.com/prospects/stats/search?level=11&level=12&level=13&level=14&level=15&level=16&pitcher_throws=R&batter_stands=&game_date_gt=&game_date_lt=&season=2017&home_away=&draft_year=&prospect=&player_type=batter&sort_by=woba&sort_order=desc&group_by=name&min_pa=&min_pitches=#results'
//creating an array for each scrape
var res = [];
var res1 = [];
var res2 = [];
var res3 = [];
//getting the MLB and FG ids from the spreadsheet
var mlbids = ids.getRange(1, 11, ids.getLastRow()).getValues();
var fgids = ids.getRange(1,9, ids.getLastRow()).getValues();
//scraping SO against RHP
var content_SO = UrlFetchApp.fetch(mb18vR_SO_url).getContentText();
var e_SO = Parser.data(content_SO).from('tbody').to('</tbody>').build();
var rows_SO = Parser.data(e_SO).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows_SO.length; i++) { //rows.length
res1[i] = [];
res1[i][0] = Parser.data(rows_SO[i]).from('/player/').to('/').build();
var SOs = Parser.data(rows_SO[i]).from('<td align="left">').to('</td>').iterate();
res1[i][1] = SOs[1];
}
//scraping wOBA against RHP
var content_wOBA = UrlFetchApp.fetch(mb18vR_wOBA_url).getContentText();
var e_wOBA = Parser.data(content_wOBA).from('tbody').to('</tbody>').build();
var rows_wOBA = Parser.data(e_wOBA).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows_wOBA.length; i++) { //rows.length
res2[i] = [];
res2[i][0] = Parser.data(rows_wOBA[i]).from('/player/').to('/').build();
var wOBAs = Parser.data(rows_wOBA[i]).from('<td align="left">').to('</td>').iterate();
res2[i][1] = wOBAs[2];
}
//scraping PA against RHP
var content = UrlFetchApp.fetch(mb18vR_PA_url).getContentText();
var e = Parser.data(content).from('tbody').to('</tbody>').build();
var rows = Parser.data(e).from('<tr class="player_row"').to('</tr>').iterate();
for (var i=0; i<rows.length; i++) { //rows.length
res[i] = [];
res[i][0] = Parser.data(rows[i]).from('/player/').to('/').build();
res[i][1] = [];
//matching the MLB_ID with FG_ID
var mlbID = res[i][0];
for(var j = 0; j<mlbids.length;j++){
if(mlbids[j] == mlbID){
res[i][1] = fgids[j];
}
}
var PAs = Parser.data(rows[i]).from('<td align="left">').to('</td>').iterate();
res[i][2] = PAs[1];
//matching the MLB_ID from PA (res) with SO (res1)
res[i][3] = 0;
for (var w=0; w<res1.length; w++) {
if (res[i][0] == res1[w][0]) {
res[i][3] = res1[w][1];
}
}
//Calculating K%
res[i][4] = res[i][3] / res[i][2]
//matching the MLB_ID from PA (res) with wOBA (res1)
res[i][5] = 0;
for (var v=0; v<res2.length; v++) {
if (res[i][0] == res2[v][0]) {
res[i][5] = res2[v][1];
}
}
}
//pasting values
mb18vR_sheet.getRange(2, 1, res.length, res[0].length).setValues(res);
}
The issue you have is that you are forcing your script to loop through large datasets many many times for each row of compared data. A better approach is to build a lookup object, which maps between a desired unique identifier and the row of the data array you want to access:
/* Make an object from an Array[][] that has a unique identifier in one of the columns.
* #param Array[][] data The 2D array of data to index, e.g. [ [r1c1, r1c2, ...], [r2c1, r2c2, ...], ... ]
* #param Integer idColumn The column in the data array that is a unique row identifier
e.g. the column index that contains the product's serial number, in a data
array that has only a single row per unique product.
#return Object {} An object that maps between an id and a row index, such that
`object[id]` = the row index for the specific row in data that has id = id
*/
function makeKey(data, idColumn) {
if(!data || !data.length || !data[0].length)
throw new ValueError("Input data argument is not Array[][]");
// Assume the first column is the column with the unique identifier if not given by the caller.
if(idColumn === undefined)
idColumn = 0;
var key = {};
for(var r = 0, rows = data.length; r < rows; ++r) {
var id = data[r][idColumn];
if (key[id])
throw new ValueError("ID is not unique for id='" + id + "'");
key[id] = r;
}
return key;
}
Usage:
var database = someSheet.getDataRange().getValues();
var lookup = makeKey(database, 3); // here we say that the 4th column has the unique values.
var newData = /* read a 2D array from somewhere */;
for(var r = 0, rows < newData.length; r < rows; ++r) {
var id = newData[r][3];
var existingIndex = lookup[id];
if (existingIndex) {
var oldDataRow = database[existingIndex];
} else {
// No existing data.
}
}
By making a lookup object for your data arrays, you no longer have to re-search them and make comparisons, because you did the search once and stored the relationship, rather than discarding it every time. Note that the key that was made is based on a specific (and unique) property of the data. Without that relationship, this particular indexing approach won't work - but a different one will.

as3 multidimensional array

Im trying to make a multidimensional array but I obtain an error ("TypeError: Error #1010: A term is undefined and has no properties.").
var matriz:Array = new Array();
for(var p:Number = 0; p<2;p++ ){
for(var q:Number = 0; q<2;q++ ){
matriz[p][q] = 0;
}
}
what am I doing wrong?
Thanks in advance!
You need to create an array within matriz[p] before you can add an array (or anything else) into it.
You can achieve what you're attempting without errors like this:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++)
{
// Create an array at matriz[p] if undefined.
if(matriz[p] == undefined) matriz[p] = [];
for(var q:Number = 0; q<2; q++)
{
matriz[p][q] = 0;
}
}
Essentially you were trying to do the same as this:
var object:Object = {};
object.nonexistantProperty.value = 10;
What Marty has said is correct, however I prefer removing the if condition and changing the code to the following:
var matriz:Array = [];
for(var p:Number = 0; p<2; p++) {
matriz[p] = [];
for(var q:Number = 0; q<2; q++) {
matriz[p][q] = 0;
}
}
public class cArray
{
private var DIM1CAP:uint=0;
private var DIM2CAP:uint=1;
private var DIM3CAP:uint=2;
private var DIM4CAP:uint=3;
private var DIM5CAP:uint=4;
public function cArray():void
{
// avoid the noid
}
// returns empty array of args.length dimensions
// 1st argument is dim 1 capacity; 2nd is dim 2, etc.
public function getArray ( ... args ):Array
{
var arr = new Array();
if ( paramsNotValid(args) )
{
return null;
}
switch (args.length)
{
case 2:
arr = get2DArray ( args[0], args[1] );
break;
case 3:
arr = get3DArray ( args[0], args[1], args[2] );
break;
case 4:
arr = get4DArray ( args[0], args[1], args[2], args[3] );
break;
case 5:
arr = get5DArray ( args[0], args[1], args[2], args[3], args[4] );
break;
default:
break;
}
return arr;
}
// returns empty 2d array of parameter specified capacity
private function get2DArray ( _1stDimCapacity:uint, _2ndDimCapacity:uint ):Array
{
var arr2d:Array = [];
var arr1d = new Array();
for ( var i:uint=0; i<_1stDimCapacity; i++ )
{
arr1d[_2ndDimCapacity-1] = undefined;
arr2d.push(arr1d);
arr1d = new Array();
}
return arr2d;
}
// returns empty 3d array of parameter specified capacity
private function get3DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint ):Array
{
var arr3d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr3d.push ( get2DArray ( dim2Cap, dim3Cap ) );
}
return arr3d;
}
// returns empty 4d array of parameter specified capacity
private function get4DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint):Array
{
var arr4d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr4d.push ( get3DArray ( dim2Cap, dim3Cap, dim4Cap ) );
}
return arr4d;
}
// returns empty 5d array of parameter specified capacity
private function get5DArray ( dim1Cap:uint,
dim2Cap:uint,
dim3Cap:uint,
dim4Cap:uint,
dim5Cap:uint):Array
{
var arr5d = new Array();
for ( var i:uint=0; i<dim1Cap; i++ )
{
arr5d.push ( get4DArray ( dim2Cap, dim3Cap, dim4Cap, dim5Cap ) );
}
return arr5d;
}
//////////////////////////////////////////////////////
private function paramsNotValid ( args:Array ):Boolean
{
if ( args.length<2 || args.length>5 )
{
return true;
}
for ( var i:uint=0; i<args.length; i++ )
{
if ( ! ( args[i]>0 ) )
{
break;
}
}
if ( i < args.length )
{
return true;
}
return false;
}
}
}
public class cMain extends MovieClip
{
var cArr:cArray = new cArray;
public function cMain():void
{
var arr2d:Array;
var arr3d:Array;
var chessBrd_4d:Array;
var arr5d:Array;
// capacity of 10 games; 150 moves/gm; white's mv or black's;
// - piece positions; move in chess notation (index 32 of
// - last dimension); commentary (index 33 of last dimension)
chessBrd_4d = cArr.getArray(10,150,2,34);
// adding data
// - 4th game, 8th move, white's move, positions of pieces
chessBrd_4d[3][7][0][0] = 'd8';
chessBrd_4d[3][7][0][1] = 'b1';
// ...
// - positions of pieces up to last one
// ...
// - last piece pos
chessBrd_4d[3][7][0][31] = 'captured';
// - actual move in chess notation
chessBrd_4d[3][7][0][32] = 'nC4';
// - annotation
chessBrd_4d[3][7][0][33] = 'blocks b pawn, ' +
'opens diag for c1 bishop, ' +
'Justin Beiber is a putz, ' +
'the president is liar'
trace ( 'piece 0 is on square ' + chessBrd_4d[3][7][0][0]);
trace ( 'piece 1 is on square ' + chessBrd_4d[3][7][0][1]);
trace ( ' ... ' )
trace ( 'piece 31 has been ' + chessBrd_4d[3][7][0][31]);
trace ( 'move: ' + chessBrd_4d[3][7][0][32]);
trace ( chessBrd_4d[3][7][0][33]);
/*
trace results:
piece 0 is on square d8
piece 1 is on square b1
...
piece 31 has been captured
move: nC4
blocks b pawn, opens diag for c1 bishop,
Justin Beiber is a putz, the president is liar
*/
/*
trace ( chessBrd_4d.length ); = 10
trace ( chessBrd_4d [ 2 ].length ); = 150
trace ( chessBrd_4d [ 2 ] [ 4 ].length ); = 2
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 1 ].length ); = 34
trace ( chessBrd_4d [ 2 ] [ 4 ] [ 0 ] .length); = 34
*/
}
}

Merge two ArrayCollection - Flex

I have two ArrayCollection and I want to merge them into one...
arr1 =
[0] -> month = 07
tot_err = 15
[1] -> month = 08
tot_err = 16
[2] -> month = 09
tot_err = 17
arr2 =
[0] -> month = 07
tot_ok = 5
[1] -> month = 08
tot_ok = 6
[2] -> month = 09
tot_ok = 7
I would like to have this array
arr3 =
[0] -> month = 07
tot_err = 15
tot_ok = 5
[1] -> month = 08
tot_err = 16
tot_ok = 6
[2] -> month = 09
tot_err = 17
tot_ok = 7
How can I do it?
EDIT:
I did this solution:
private function mergeArrays(a:ArrayCollection, b:ArrayCollection):ArrayCollection
{
for (var i:int=0;i<a.length;i++)
for each(var item:Object in b)
{
if( a[i].month == item.month){
a[i].tot_err = item.tot_err;
}
}
return a;
}
But there is an important problem, if array2 (b) has a item.month that there isn't in the array1 (a) the value is lost...
private function mergeArrays(a:ArrayCollection, b:ArrayCollection):ArrayCollection
{
var result:ArrayCollection = new ArrayCollection();
var months:Dictionary = new Dictionary();
for (var i:int = 0; i < a.length; i++)
{
var mergedItem:Object = new Object();
mergedItem.month = a[i].month;
mergedItem.tot_ok = a[i].tot_ok;
mergedItem.tot_err = null;
for (var j:int = 0; j < b.length; j++)
{
if(a[i].month == b[j].month)
{
mergedItem.tot_err = b[j].tot_err;
}
}
month[mergedItem.month] = true;
result.addItem(mergedItem);
}
// so far we have handled all occurrences between a and b,
// now we need to handle the items from b that are left
for each (var bItem:Object in b)
{
mergedItem = new Object();
mergedItem.month = bItem.month;
mergedItem.tot_err = bItem.tot_err;
mergedItem.tot_ok = null;
if (months[mergedItem.month] == null)
{
month[mergedItem.month] = true;
result.addItem(mergedItem);
}
}
return result;
}
if( a[i].month == item.month){
a[i].tot_err = item.tot_err;
// remove the item from b here. dontknow arraycollection
// should be like b.remove(item);
}
after for loops you can check if "b" still have elements, so you can add them to "a", dont forget to give "b" array objects a default tot_ok value. And another thing if an object in "a" that doesnt have equalivant in "b" you can use this.
private function mergeArrays(a:ArrayCollection, b:ArrayCollection):ArrayCollection
{
var ex:Boolean = true;
for (var i:int=0;i<a.length;i++){
for each(var item:Object in b)
{
if( a[i].month == item.month){
a[i].tot_err = item.tot_err;
ex = true;
}else{
ex = false;
}
}
if(!ex){
// give a default value here.
a[i].tot_err = 0;
}
}
return a;
}
private function mergeArrayCollections(a:ArrayCollection, b:ArrayCollection):ArrayCollection {
var c:ArrayCollection=new ArrayCollection(b.toArray()); //clone b so as not to modify b
//This loop handles all objects common to a and b
for each(var o:Object in a) {
for (var i:int=0; i<c.length; i++) {
var p:Object=c.getItemAt(i);
if(o.month==p.month) {
//if the month is the same then add the property to a
o.tot_ok=p.tot_ok;
c.removeItemAt(i);
break;
}
}
}
//This loop adds the leftover items from c to a
for each(var q:Object in c) {
q.tot_err=-1; //add this so that all objects in a are uniform
a.addItem(q);
}
return a; //Unnecessary return, a will be modified by reference
}
if array2 (b) has a item.month that there isn't in the array1 (a) use addItem() method to add new object to array1 (a) ;

Iterating each pixel of a Bitmap image in ActionScript

Is it possible to iterate each pixel of a bitmap image? Eventually what I'm trying to achieve is that I need to get the coordinate values of each pixel of a bitmap image and change the color of those pixels according to their coordinate values. As I see it, I need to use the getPixels() method but I still did not understand exactly what I should do.
( too slow :) )
so this is the sae as above with a linear loop instead of 2 nested loops.
//creates a new BitmapData, with transparency, white 0xFFFFFF
var bd:BitmapData = new BitmapData( 100, 100, false, 0xFFFFFF );
//stores the width and height of the image
var w:int = bd.width;
var h:int = bd.height;
var i:int = w * h;
var x:int, y:int, col;
//decremental loop are said to be faster :)
while ( i-- )
{
//this is the position of each pixel in x & y
x = i % w;
y = int( i / w );
//gets the current color of the pixel ( 0xFFFFFF )
col = bd.getPixel( x, y );
//assign the 0xFF0000 ( red ) color to the pixel
bd.setPixel( x, y, 0xFF0000 );
}
addChild( new Bitmap( bd ) );//a nice red block
note that if you're using a bitmapData with an alpha channel (say if you load the image, the alpha will be turned on automatically ) you 'll have to use
bd.getPixel32( x, y );// returns a uint : 0xFF000000
//and
bd.setPixel32( x, y, UINT );// 0xFF000000
EDIT : I 've done a quick bench :
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.utils.getTimer;
public class pixels extends Sprite
{
private var bd:BitmapData = new BitmapData( 100, 100, false, 0xFFFFFF );
public function pixels()
{
var i:int, total:int = 100, t:int = 0;
t = getTimer();
i = total;
while( i-- )
{
whileLoop( bd );
}
trace( 'while:', getTimer() - t );
t = getTimer();
i = total;
while( i-- )
{
forLoop( bd );
}
trace( 'for:', getTimer() - t );
}
private function forLoop( bd:BitmapData ):void
{
var i:int, j:int;
var col:int;
for ( i = 0; i < bd.width; i++ )
{
for ( j = 0; j < bd.height; j++ )
{
col = bd.getPixel( i, j ); // +/- 790 ms
}
}
//for ( i = 0; i < bd.width; i++ ) for ( j = 0; j < bd.height; j++ ) col = bd.getPixel( i, j ); // +/-530 ms
//var w:int = bd.width;
//var h:int = bd.height;
//for ( i = 0; i < w; i++ ) for ( j = 0; j < h; j++ ) col = bd.getPixel( i, j ); // +/-250 ms
}
private function whileLoop( bd:BitmapData ):void
{
var w:int = bd.width;
var h:int = bd.height;
var i:int = w * h;
var col:int;
while ( i-- )
{
col = bd.getPixel( i % w, int( i / w ) ); // +/- 580 ms
}
//while ( i-- ) col = bd.getPixel( i % w, int( i / w ) ); // +/- 330 ms
}
}
}
for 100 * ( 100 * 100 ) getPixel, the fastest (on my machine) is the one-line for loop with local variables. ( +/- 250 ms ) then the one-line while( +/- 330 ms ) :)
storing local variables w and h for width and height makes the for loops twice faster :)
good to know
If, as you say, you are only setting the pixels based on their x and y, you need neither getPixel() nor getPixels()!
myBitmapData.lock();
for( var j:int = 0; j < myBitmapData.height; j++ )
{
for( var i:int = 0; i < myBitmapData.width; i++ )
{
var alpha:uint = 0xFF000000; // Alpha is always 100%
var red:uint = 0x00FF0000 * ( i / myBitmapData.width ); // Set red based on x
var green:uint = 0x0000FF00 * ( j / myBitmapData.height ); // Set green based on y
var newColor:uint = alpha + red + green; // Add the components
// Set the new pixel value (setPixel32() includes alpha, e.g. 0xFFFF0000 => alpha=FF, red=FF, green=00, blue=00)
myBitmapData.setPixel32( i, j, newColor );
}
}
myBitmapData.unlock();
If, however, you want to read the pixels' current value, let me join the speed competition.
In addition to earlier answers, here's much more speed increase!
Instead of numerous calls to getPixel(), you can use getPixels() to get a byteArray of the pixel data.
myBitmapData.lock();
var numPixels:int = myBitmapData.width * myBitmapData.height;
var pixels:ByteArray = myBitmapData.getPixels( new Rectangle( 0, 0, myBitmapData.width, myBitmapData.height ) );
for( var i:int = 0; i < numPixels; i++ )
{
// Read the color data
var color:uint = pixels.readUnsignedInt();
// Change it if you like
// Write it to the pixel (setPixel32() includes alpha, e.g. 0xFFFF0000 => alpha=FF, red=FF, green=00, blue=00)
var theX:int = i % myBitmapData.width;
myBitmapData.setPixel32( theX, ( i - theX ) / myBitmapData.width, color );
}
myBitmapData.unlock();
You need a BitmapData object. Then, it's a simple straight-forward nested loop :
var pix : int; //AS3 uses int even for uint types
for (var x:int = 0; x < myBitmapData.width; x++)
{
for (var y:int = 0; y < myBitmapData.height; y++)
{
// This'll get you the pixel color as RGB
pix = myBitmapData.getPixel(x,y);
// To change the color, use the setPixel method + the uint corresponding
// to the new color.
}
}