public CharacterBitmap(byte[] data)
        {
            //Load the data into the byte array
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    Character[j] = data[i];
                    i++;
                }
            }

            //Now generate a bitmap somehow
            CharacterImage = new WriteableBitmap(8, 8, 96, 96, PixelFormats.Bgr32, null);
            CharacterImage.Lock();
            for(int i = 0; i < 8; i++)
            {
                if((Character[i] & 0x10) == 0x10)
                {
                    CharacterImage.SetPixel(3, i, Colors.White);
                } else
                {
                    CharacterImage.SetPixel(3, i, Colors.Black);
                }
                if ((Character[i] & 0x08) == 0x08)
                {
                    CharacterImage.SetPixel(4, i, Colors.White);
                }
                else
                {
                    CharacterImage.SetPixel(4, i, Colors.Black);
                }
                if ((Character[i] & 0x04) == 0x04)
                {
                    CharacterImage.SetPixel(5, i, Colors.White);
                }
                else
                {
                    CharacterImage.SetPixel(5, i, Colors.Black);
                }
                if ((Character[i] & 0x02) == 0x02)
                {
                    CharacterImage.SetPixel(6, i, Colors.White);
                }
                else
                {
                    CharacterImage.SetPixel(6, i, Colors.Black);
                }
                if ((Character[i] & 0x01) == 0x01)
                {
                    CharacterImage.SetPixel(7, i, Colors.White);
                }
                else
                {
                    CharacterImage.SetPixel(7, i, Colors.Black);
                }
            }
            CharacterImage.Unlock();
        }
 private void PreviewImage_OnLoaded(object sender, RoutedEventArgs e)
 {
     _bitmap = BitmapFactory.New(500, 500);
     for (var y = 0; y < 500; ++y)
     {
         for (var x1 = 0; x1 < 250; ++x1)
         {
             _bitmap.SetPixel(x1,y,WriteableBitmapExtensions.ConvertColor(Colors.DodgerBlue));
             _bitmap.SetPixel(x1+250, y, WriteableBitmapExtensions.ConvertColor(Colors.SeaGreen));
         }
     }
     _bitmap.FillEllipseCentered(225, 225, 50, 50, WriteableBitmapExtensions.ConvertColor(0.5, Colors.Red), true);
     //_bitmap.FillRectangle(200, 200, 250, 250, WriteableBitmapExtensions.ConvertColor(0.5, Colors.Red), true);
     PreviewImage.Source = _bitmap;
 }
 protected BaseTool(WorldViewModel worldViewModel)
 {
     _wvm = worldViewModel;
     _preview = new WriteableBitmap(1, 1, 96, 96, PixelFormats.Bgra32, null);
     _preview.Clear();
     _preview.SetPixel(0, 0, 127, 0, 90, 255);
 }
        public SelectionTool(WorldViewModel worldViewModel)
        {
            _wvm = worldViewModel;
            _preview = new WriteableBitmap(1, 1, 96, 96, PixelFormats.Bgra32, null);
            _preview.Clear();
            _preview.SetPixel(0, 0, 127, 0, 90, 255);

            Icon = new BitmapImage(new Uri(@"pack://application:,,,/TEditXna;component/Images/Tools/shape_square.png"));
            Name = "Selection";
            IsActive = false;
        }
        public static async Task<WriteableBitmap> ToBitmapImageAsync(this BitmapHolder holder)
        {
            if (holder == null || holder.Pixels == null)
                return null;

            WriteableBitmap writeableBitmap = null;

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
            {
                writeableBitmap = new WriteableBitmap(holder.Width, holder.Height);
                
                for (int x = 0; x < holder.Width; x++)
                    for (int y = 0; y < holder.Height; y++)
                        writeableBitmap.SetPixel(x, y, holder.Pixels[x + y * holder.Width]);

                writeableBitmap.Invalidate();
            });

            return writeableBitmap;
        }
Exemple #6
0
        private static async void captureSnapshot(ushort[] pixeldata, int pitch, string filename)
        {
            WriteableBitmap bitmap = new WriteableBitmap(pitch / 2, (int)pixeldata.Length / (pitch / 2));
            int x = 0;
            int y = 0;
            for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
            {
                ushort pixel = pixeldata[i];
                byte r = (byte)((pixel & 0xf800) >> 11);
                byte g = (byte)((pixel & 0x07e0) >> 5);
                byte b = (byte)(pixel & 0x001f);
                r = (byte)((255 * r) / 31);
                g = (byte)((255 * g) / 63);
                b = (byte)((255 * b) / 31);
                bitmap.SetPixel(x, y, r, g, b);
                x++;
                if (x >= bitmap.PixelWidth)
                {
                    y++;
                    x = 0;
                }
            }
            String snapshotName = filename.Substring(0, filename.Length - 3) + "jpg";
            //StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(ROM_DIRECTORY);
            ////StorageFolder saveFolder = await folder.GetFolderAsync(SAVE_DIRECTORY);
            //StorageFolder shared = await folder.GetFolderAsync("Shared");
            //StorageFolder shellContent = await shared.GetFolderAsync("ShellContent");
            //StorageFile file = await shellContent.CreateFileAsync(snapshotName, CreationCollisionOption.ReplaceExisting);

            try
            {
                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream("/Shared/ShellContent/" + snapshotName, System.IO.FileMode.Create, iso))
                {
                    bitmap.SaveJpeg(fs, bitmap.PixelWidth, bitmap.PixelHeight, 0, 90);
                    //await fs.FlushAsync();
                    fs.Flush(true);
                }
                ROMDatabase db = ROMDatabase.Current;
                ROMDBEntry entry = db.GetROM(filename);
                entry.SnapshotURI = "Shared/ShellContent/" + snapshotName;
                db.CommitChanges();

                UpdateLiveTile();

                UpdateROMTile(filename);
            }
            catch (Exception)
            {
            }



            //try
            //{
            //    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            //    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            //    {
            //        bitmap.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 90);
            //        byte[] bytes = ms.ToArray();
            //        DataWriter writer = new DataWriter(stream);
            //        writer.WriteBytes(bytes);
            //        await writer.StoreAsync();
            //        writer.DetachStream();
            //        await stream.FlushAsync();
            //    }

            //    ROMDatabase db = ROMDatabase.Current;
            //    ROMDBEntry entry = db.GetROM(filename);
            //    entry.SnapshotURI = "Shared/ShellContent/" + snapshotName;
            //    db.CommitChanges();
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show(e.Message);
            //}

            //await file.CopyAsync(shellContent);
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight;
            if ((int)screenHeight == 0)
                throw new Exception("screenHeight");
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;
            mMainImage = new Image();

            mainPage.Width = screenWidth;
            mainPage.Height = screenHeight;
            mMainImage.Width = screenWidth;
            mMainImage.Height = screenHeight;
            mainPage.Content = mMainImage;

            mClipRect.X = 0.0;
            mClipRect.Y = 0.0;
            mClipRect.Width = screenWidth;
            mClipRect.Height = screenHeight;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mMainImage.Source = mFrontBuffer;

            // clear front and backbuffer.
            for (int i = 0; i < mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight; i++)
            {
                mBackBuffer.Pixels[i] = mBackBuffer.Pixels[i] = (int)(0xff<<24);
            }

            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));
                return oldColor & 0xffffff;
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                mClipRect.X = x;
                mClipRect.Y = y;
                mClipRect.Width = w;
                mClipRect.Height = h;
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
                Memory mem = core.GetDataMemory();
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height);
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                //System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                // this function has a bug (it only fills one pixel less than the image.)
                //mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    (int)mClipRect.X, (int)mClipRect.Y, (int)mClipRect.Width, (int)mClipRect.Height,
                    out x, out y, out w, out h);

                if (w <= 0 || h <= 0)
                    return;

                int index = x + y * mCurrentDrawTarget.PixelWidth;
                while(h-- != 0)
                {
                    int width = w;
                    while(width-- != 0)
                    {
                        mCurrentDrawTarget.Pixels[index] = (int)mCurrentColor;
                        index++;
                    }
                    index += -w + mCurrentDrawTarget.PixelWidth;
                }
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1);
                GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2);
                if(!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X+mClipRect.Width),
                    (int)mClipRect.Y, (int)(mClipRect.Y+mClipRect.Height)))
                    return;

                mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor);
            };

            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0) return;
                DrawText(text, left, top);
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0) return;

                DrawText(text, left, top);
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {

                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex) return oldDrawTarget;
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return oldDrawTarget;
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return oldDrawTarget;
            };

            syscalls.maGetScrSize = delegate()
            {
                return MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                if (src == null)
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                int w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return MoSync.Util.CreateExtent(w, h);
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Rect srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode, mClipRect);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);

                    for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
                    {
                        bitmap.Pixels[i] = (int)(0xff << 24);
                    }
                });

                if (bitmap == null) return MoSync.Constants.RES_OUT_OF_MEMORY;
                res.SetInternalObject(bitmap);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        bitmap = new WriteableBitmap(width, height);
                    });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels = bitmap.Pixels;
                    int numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                res.SetInternalObject(bitmap);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int dstX = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x);
                int dstY = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y);
                int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int[] pixels = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4; // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int lineDst = _dst;
                byte[] data = src.ToByteArray(srcRectY * src.PixelWidth,
                    srcRectH * src.PixelWidth); // BlockCopy?
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                        lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                if (res == null)
                    return MoSync.Constants.RES_BAD_INPUT;
                Stream bin = (Stream)res.GetInternalObject();
                if (bin == null)
                    return MoSync.Constants.RES_BAD_INPUT;
                BoundedStream s = new BoundedStream(bin, _offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();

                if (bitmap == null)
                    return MoSync.Constants.RES_BAD_INPUT;

                Resource imageRes = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                imageRes.SetInternalObject(bitmap);
                imageRes.SetResourceType(MoSync.Constants.RT_IMAGE);
                return MoSync.Constants.RES_OK;
            };
        }
 /// <summary>
 /// Converts a WritableBitmap to grayscale image
 /// </summary>
 public static WriteableBitmap ToGrayScale(WriteableBitmap bmp)
 {
     for (int i = 0; i < bmp.PixelHeight; i++)
     {
         for (int j = 0; j < bmp.PixelWidth; j++)
         {
             byte grayScale = Convert.ToByte((bmp.GetPixel(j, i).R * 0.3) + (bmp.GetPixel(j, i).G * 0.59) + (bmp.GetPixel(j, i).B * 0.11));
             Color c = Color.FromArgb(255, grayScale, grayScale, grayScale);
             bmp.SetPixel(j, i, c);
         }
     }
     return bmp;
 }
 private void btnOpen_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.Filter = "JPEG,PNG,BMPファイル (*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";
     ofd.Multiselect = false;
     if (ofd.ShowDialog() != true) return;
     string fn = ofd.File.Name.ToLower();
     IImageDecoder dec;
     if (fn.EndsWith(".jpg"))
     {
         dec = new JpegDecoder();
     }
     else if (fn.EndsWith(".png"))
     {
         dec = new PngDecoder();
     }
     else if (fn.EndsWith(".bmp"))
     {
         dec = new BmpDecoder();
     }
     else
     {
         MessageBox.Show("エラー");
         return;
     }
     try
     {
         FileStream fs = ofd.File.OpenRead();
         ImageTools.Image img = new ImageTools.Image();
         dec.Decode(img, fs);
         if (img.Width < 50 || img.Height < 50)
         {
             MessageBox.Show("画像サイズが小さすぎます");
             return;
         }
         WriteableBitmap wb = new WriteableBitmap(img.Width, img.Height);
         byte[] data = img.GetPixels();
         for (int y = 0; y < img.Height; y++)
         {
             for (int x = 0; x < img.Width; x++)
             {
                 int idx = (x + y * img.Width) * 4;
                 wb.SetPixel(x, y, Color.FromArgb(data[idx + 3], data[idx], data[idx + 1], data[idx + 2]));
             }
         }
         SetImage(wb);
         fs.Close();
     }
     catch
     {
         MessageBox.Show("エラー");
     }
 }
 public void Render(List<Vector2> stars, Color color, int size, WriteableBitmap screen)
 {
     if (size <= 1)
     {
         foreach (var star in stars)
         {
             // TODO: Outside bounds of array error can occur here! Float accuracy adding up?
             screen.SetPixel((int)star.X, (int)star.Y, color);
         }
     }
     else
     {
         foreach (var star in stars)
         {
             screen.FillRectangleFixed((int)star.X, (int)star.Y, (int)star.X + size, (int)star.Y + size, color);
         }
     }
 }
Exemple #11
0
        public override WriteableBitmap PreviewTool()
        {
            var bmp = new WriteableBitmap(
                1,
                1,
                96,
                96,
                PixelFormats.Bgra32,
                null);

            bmp.Clear();
            bmp.SetPixel(0, 0, 127, 0, 90, 255);
            return bmp;
        }
        public void SaveFalseColor(string filename)
        {
            var wbmp = new WriteableBitmap(Size.X, Size.Y, 96, 96, PixelFormats.Bgra32, null);

            for (int y = 0; y < Size.Y; y++)
            {

                for (int x = 0; x < Size.X; x++)
                {
                    var curtile = Tiles[x, y];
                    byte a = TileArgsToByte(curtile);
                    byte r = curtile.Type;
                    byte g = curtile.Wall;
                    byte b = curtile.Liquid;

                    wbmp.SetPixel(x, y, a, r, g, b);
                }
            }
            wbmp.SavePng(filename);
        }
        public void RenderBuffer()
        {
            double scale = Math.Max((double)Size.X / ClipboardRenderSize, (double)Size.Y / ClipboardRenderSize);

            int previewX = this.Size.X;
            int previewY = this.Size.Y;
            if (scale > 1.0)
            {
                previewX = (int)MathHelper.Clamp((float)Math.Min(ClipboardRenderSize, this.Size.X / scale), 1, ClipboardRenderSize);
                previewY = (int)MathHelper.Clamp((float)Math.Min(ClipboardRenderSize, this.Size.Y / scale), 1, ClipboardRenderSize);
            }
            else
                scale = 1;

            var bmp = new WriteableBitmap(previewX, previewY, 96, 96, PixelFormats.Bgra32, null);
            for (int x = 0; x < previewX; x++)
            {
                int tileX = (int)MathHelper.Clamp((float)(scale * x), 0, this.Size.X - 1);

                for (int y = 0; y < previewY; y++)
                {
                    int tileY = (int)MathHelper.Clamp((float)(scale * y), 0, this.Size.Y - 1);

                    var color = Render.PixelMap.GetTileColor(Tiles[tileX, tileY], Microsoft.Xna.Framework.Color.Transparent);
                    bmp.SetPixel(x, y, color.A, color.R, color.G, color.B);
                }
            }
            Preview = bmp;
            RenderScale = scale;
        }
        private void DrawGrid(WriteableBitmap writeableBitmap)
        {
            Color color = Colors.White;
            color.A = 50;
            switch (GridType)
            {
                case 1:
                {
                    for (int i = 1; i < 3; i++)
                    {
                        writeableBitmap.DrawLine(0, (int) ((writeableBitmap.Height/3)*i),
                            (int) writeableBitmap.Width,
                            (int) ((writeableBitmap.Height/3)*i), color);
                        writeableBitmap.DrawLine((int) ((writeableBitmap.Width/3)*i), 0,
                            (int) ((writeableBitmap.Width/3)*i),
                            (int) writeableBitmap.Height, color);
                    }
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 2:
                {
                    for (int i = 1; i < 10; i++)
                    {
                        writeableBitmap.DrawLine(0, (int) ((writeableBitmap.Height/10)*i),
                            (int) writeableBitmap.Width,
                            (int) ((writeableBitmap.Height/10)*i), color);
                        writeableBitmap.DrawLine((int) ((writeableBitmap.Width/10)*i), 0,
                            (int) ((writeableBitmap.Width/10)*i),
                            (int) writeableBitmap.Height, color);
                    }
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 3:
                {
                    writeableBitmap.DrawLineDDA(0, 0, (int) writeableBitmap.Width,
                        (int) writeableBitmap.Height, color);

                    writeableBitmap.DrawLineDDA(0, (int) writeableBitmap.Height,
                        (int) writeableBitmap.Width, 0, color);
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 4:
                {
                    writeableBitmap.DrawLineDDA(0, (int) (writeableBitmap.Height/2), (int) writeableBitmap.Width,
                        (int) (writeableBitmap.Height/2), color);

                    writeableBitmap.DrawLineDDA((int) (writeableBitmap.Width/2), 0,
                        (int) (writeableBitmap.Width/2), (int) writeableBitmap.Height, color);
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                default:
                    try
                    {
                        if (GridType > 4)
                        {
                            string filename = Path.Combine(ServiceProvider.Settings.OverlayFolder,
                                SelectedOverlay + ".png");
                            if (File.Exists(filename))
                            {
                                BitmapImage bitmapSource = new BitmapImage();
                                bitmapSource.BeginInit();
                                bitmapSource.UriSource = new Uri(filename);
                                bitmapSource.EndInit();
                                WriteableBitmap overlay = BitmapFactory.ConvertToPbgra32Format(bitmapSource);
                                writeableBitmap.Blit(
                                    new Rect(0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight),
                                    overlay,
                                    new Rect(0, 0, overlay.PixelWidth, overlay.PixelHeight));
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                    break;
            }
        }
 public void RenderBuffer()
 {
     var bmp = new WriteableBitmap(Size.X, Size.Y, 96, 96, PixelFormats.Bgra32, null);
     for (int x = 0; x < Size.X; x++)
     {
         for (int y = 0; y < Size.Y; y++)
         {
             var color = Render.PixelMap.GetTileColor(Tiles[x, y], Microsoft.Xna.Framework.Color.Transparent);
             bmp.SetPixel(x, y, color.A, color.R, color.G, color.B);
         }
     }
     Preview = bmp;
 }
Exemple #16
0
        /// <summary>
        /// Converts this ByteMatrix to a black and white bitmap.
        /// </summary>
        /// <returns>A black and white bitmap converted from this ByteMatrix.</returns>
        public WriteableBitmap ToBitmap()
        {
            const byte BLACK = 0;
            const byte WHITE = 255;
            sbyte[][] array = Array;
            int width = Width;
            int height = Height;
            var pixels = new byte[width*height];

            var bmp = new WriteableBitmap(width, height);

            for (int y = 0; y < height; y++)
            {
                int offset = y*width;
                for (int x = 0; x < width; x++)
                {
                    byte c = array[y][x] == 0 ? BLACK : WHITE;
                    bmp.SetPixel(x, y, c);
                }
            }

            //Return the bitmap
            return bmp;
        }
Exemple #17
0
        public static void floodFill(Point pt, Color targetColor, Color replacementColor, WriteableBitmap compressedBitmap, WriteableBitmap outputBitmap)
        {
            Queue<Point> q = new Queue<Point>();

            maxLeft = compressedBitmap.PixelWidth;
            //System.Diagnostics.Debug.WriteLine(maxLeft);
            maxRight = 0;
            maxTop = compressedBitmap.PixelHeight;
            //System.Diagnostics.Debug.WriteLine("while filling" + maxTop);
            maxBottom = 0;

            if (!Common.ColorMatch(compressedBitmap.GetPixel((int)pt.X, (int)pt.Y), targetColor) || Common.ColorMatch(compressedBitmap.GetPixel((int)pt.X, (int)pt.Y), replacementColor))
            {
                return;
            }

            q.Enqueue(pt);

            while (q.Count > 0)
            {
                Point n = q.Dequeue();

                if (Common.ColorMatch(compressedBitmap.GetPixel((int)n.X, (int)n.Y), targetColor))
                {
                    Point west = n;
                    Point east = n;

                    while ((west.X >= 0) && (west.X < compressedBitmap.PixelWidth) && Common.ColorMatch(compressedBitmap.GetPixel((int)west.X, (int)west.Y), targetColor))
                    {
                        west.X--;
                    }
                    while ((east.X >= 0) && (east.X < compressedBitmap.PixelWidth) && Common.ColorMatch(compressedBitmap.GetPixel((int)east.X, (int)east.Y), targetColor))
                    {
                        east.X++;
                    }
                    west.X++;
                    east.X--;

                    if (west.X < maxLeft)
                    {
                        maxLeft = west.X;
                    }

                    if (east.X > maxRight)
                    {
                        maxRight = east.X;
                    }

                    for (int i = (int)west.X; i <= east.X; i++)
                    {
                        compressedBitmap.SetPixel(i, (int)west.Y, replacementColor);
                        outputBitmap.SetPixel(i, (int)west.Y, replacementColor);
                        if ((i >= 0) && (i < compressedBitmap.PixelWidth) && (west.Y + 1 >= 0 && west.Y + 1 < compressedBitmap.PixelHeight) && Common.ColorMatch(compressedBitmap.GetPixel(i, (int)west.Y + 1), targetColor))
                        {
                            if (west.Y + 1 > maxBottom)
                            {
                                maxBottom = west.Y + 1;
                            }

                            q.Enqueue(new Point(i, west.Y + 1));
                        }
                        if ((i >= 0) && (i < compressedBitmap.PixelWidth) && (west.Y - 1 >= 0 && west.Y - 1 < compressedBitmap.PixelHeight) && Common.ColorMatch(compressedBitmap.GetPixel(i, (int)west.Y - 1), targetColor))
                        {
                            if (west.Y - 1 < maxTop)
                            {
                                maxTop = west.Y - 1;
                            }

                            q.Enqueue(new Point(i, west.Y - 1));
                        }
                    }
                }
            }
        }
        public AdvGamePage()
        {
            InitializeComponent();

            var fileStream1 = Application.GetResourceStream(new Uri("TestImages/TestingUpper.png", UriKind.Relative));
            var s1 = new BitmapImage();
            using (var stream = fileStream1.Stream)
            {
                s1.SetSource(stream);
            }

            var upper = new WriteableBitmap(s1);

            var fileStream2 = Application.GetResourceStream(new Uri("TestImages/TestingLower.png", UriKind.Relative));
            var s2 = new BitmapImage();
            using (var stream = fileStream2.Stream)
            {
                s2.SetSource(stream);
            }

            var lower = new WriteableBitmap(s2);

            var upperEx = upper.GetBitmapContext();
            var lowerEx = lower.GetBitmapContext();

            UpperImage.Source = upper;
            LowerImage.Source = lower;

            upper.ForEach((x, y, color) =>
                {
                    var lowerColor = lower.GetPixel(x, y);
                    return new Color
                        {
                            R = (byte) (color.R - lowerColor.R),
                            G = (byte) (color.G - lowerColor.G),
                            B = (byte) (color.B - lowerColor.B),
                            A = color.A
                        };
                });
            upper.Invalidate();

            var changesPixels = new List<Point>();

            upper.ForEach((x, y, color) =>
                {
                    if (upper.GetPixel(x, y).R != 0)
                    {
                        lower.FillEllipseCentered(x, y, 10, 10, Colors.Red);
                        changesPixels.Add(new Point(x, y));
                    }

                    return color;
                });
            lower.Invalidate();

            //var indicator = new bool[480, 320];
            var startingPoint = changesPixels[0];
            var newPointToBeInvestigate = new List<Point> { startingPoint };
            changesPixels.Remove(startingPoint);
            //indicator[(int)startingPoint.X, (int)startingPoint.Y] = true;

            System.Diagnostics.Debug.WriteLine(DateTime.Now);

            var i = 0;
            while (newPointToBeInvestigate.Count > 0 && i < newPointToBeInvestigate.Count)
            {
                var newPixels = changesPixels.Where(p => DistanceBetweenPoints(newPointToBeInvestigate[i], p)).ToList();

                foreach (var np in newPixels)
                {
                    changesPixels.Remove(np);
                    newPointToBeInvestigate.Add(np);
                }

                //foreach (var newP in newPixels.Where(newP => !indicator[(int)newP.X, (int)newP.Y]))
                //{
                //    indicator[(int)newP.X, (int)newP.Y] = true;
                //}

                i++;

            }
            System.Diagnostics.Debug.WriteLine(DateTime.Now);

            foreach (var changeP in newPointToBeInvestigate)
            {
                lower.SetPixel((int)changeP.X, (int)changeP.Y, Colors.Green);
            }

            lower.Invalidate();
        }
Exemple #19
0
        public Tetris(WriteableBitmap wbm)
        {
            this.wbm = wbm;
            this.wb = BitmapFactory.New(wbm.PixelWidth / 2, wbm.PixelHeight / 2);

            for (int i = 0; i < wb.PixelHeight; i++)
            {
                for (int j = 0; j < wb.PixelWidth; j++)
                {

                    wb.SetPixel(j, i,Colors.Black);
                }
            }
            Rows = this.wb.PixelHeight;
            Cols = this.wb.PixelWidth;
            _score = 0;
            _level = 1;

            Level = _level;
            LinesFilled = 0;
            currTetramino = new Tetramino();
            currTetraminoDraw();
        }
        private void DrawGrid(WriteableBitmap writeableBitmap)
        {
            System.Windows.Media.Color color = Colors.White;
            color.A = 50;

            if (OverlayActivated)
            {
                if ((SelectedOverlay != null && File.Exists(SelectedOverlay)) || OverlayUseLastCaptured)
                {
                    if (OverlayUseLastCaptured)
                    {
                        if (File.Exists(ServiceProvider.Settings.SelectedBitmap.FileItem.LargeThumb) &&
                            _lastOverlay != ServiceProvider.Settings.SelectedBitmap.FileItem.LargeThumb)
                        {
                            _lastOverlay = ServiceProvider.Settings.SelectedBitmap.FileItem.LargeThumb;
                            _overlayImage = null;
                        }
                    }

                    if (_overlayImage == null)
                    {
                        BitmapImage bitmapSource = new BitmapImage();
                        bitmapSource.DecodePixelWidth = writeableBitmap.PixelWidth;
                        bitmapSource.BeginInit();
                        bitmapSource.UriSource = new Uri(OverlayUseLastCaptured ? _lastOverlay : SelectedOverlay);
                        bitmapSource.EndInit();
                        _overlayImage = BitmapFactory.ConvertToPbgra32Format(bitmapSource);
                        _overlayImage.Freeze();
                    }
                    int x = writeableBitmap.PixelWidth*OverlayScale/100;
                    int y = writeableBitmap.PixelHeight*OverlayScale/100;
                    int xx = writeableBitmap.PixelWidth*OverlayHorizontal/100;
                    int yy = writeableBitmap.PixelWidth*OverlayVertical/100;
                    System.Windows.Media.Color transpColor = Colors.White;

                    //set color transparency for blit only the alpha chanel is used from transpColor
                    if (OverlayTransparency < 100)
                        transpColor = System.Windows.Media.Color.FromArgb((byte) (0xff*OverlayTransparency/100d), 0xff, 0xff, 0xff);
                    writeableBitmap.Blit(
                        new Rect(0 + (x / 2) + xx, 0 + (y / 2) + yy, writeableBitmap.PixelWidth - x,
                            writeableBitmap.PixelHeight - y),
                        _overlayImage,
                        new Rect(0, 0, _overlayImage.PixelWidth, _overlayImage.PixelHeight), transpColor,
                        WriteableBitmapExtensions.BlendMode.Alpha);
                }
            }

            switch (GridType)
            {
                case 1:
                    {
                        for (int i = 1; i < 3; i++)
                        {
                            writeableBitmap.DrawLine(0, (int)((writeableBitmap.Height / 3) * i),
                                (int)writeableBitmap.Width,
                                (int)((writeableBitmap.Height / 3) * i), color);
                            writeableBitmap.DrawLine((int)((writeableBitmap.Width / 3) * i), 0,
                                (int)((writeableBitmap.Width / 3) * i),
                                (int)writeableBitmap.Height, color);
                        }
                        writeableBitmap.SetPixel((int)(writeableBitmap.Width / 2), (int)(writeableBitmap.Height / 2), 128,
                            Colors.Red);
                    }
                    break;
                case 2:
                    {
                        for (int i = 1; i < 10; i++)
                        {
                            writeableBitmap.DrawLine(0, (int)((writeableBitmap.Height / 10) * i),
                                (int)writeableBitmap.Width,
                                (int)((writeableBitmap.Height / 10) * i), color);
                            writeableBitmap.DrawLine((int)((writeableBitmap.Width / 10) * i), 0,
                                (int)((writeableBitmap.Width / 10) * i),
                                (int)writeableBitmap.Height, color);
                        }
                        writeableBitmap.SetPixel((int)(writeableBitmap.Width / 2), (int)(writeableBitmap.Height / 2), 128,
                            Colors.Red);
                    }
                    break;
                case 3:
                    {
                        writeableBitmap.DrawLineDDA(0, 0, (int)writeableBitmap.Width,
                            (int)writeableBitmap.Height, color);

                        writeableBitmap.DrawLineDDA(0, (int)writeableBitmap.Height,
                            (int)writeableBitmap.Width, 0, color);
                        writeableBitmap.SetPixel((int)(writeableBitmap.Width / 2), (int)(writeableBitmap.Height / 2), 128,
                            Colors.Red);
                    }
                    break;
                case 4:
                    {
                        writeableBitmap.DrawLineDDA(0, (int)(writeableBitmap.Height / 2), (int)writeableBitmap.Width,
                            (int)(writeableBitmap.Height / 2), color);

                        writeableBitmap.DrawLineDDA((int)(writeableBitmap.Width / 2), 0,
                            (int)(writeableBitmap.Width / 2), (int)writeableBitmap.Height, color);
                        writeableBitmap.SetPixel((int)(writeableBitmap.Width / 2), (int)(writeableBitmap.Height / 2), 128,
                            Colors.Red);
                    }
                    break;
                default:
                    break;
            }

            if (ShowRuler && NoSettingArea)
            {
                int x1 = writeableBitmap.PixelWidth * (HorizontalMin) / 1000;
                int x2 = writeableBitmap.PixelWidth * (HorizontalMin+HorizontalMax) / 1000;
                int y2 = writeableBitmap.PixelHeight * (VerticalMin+VerticalMax) / 1000;
                int y1 = writeableBitmap.PixelHeight * VerticalMin / 1000;

                writeableBitmap.FillRectangle2(0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, System.Windows.Media.Color.FromArgb(128, 128, 128, 128));
                writeableBitmap.FillRectangleDeBlend(x1, y1, x2, y2, System.Windows.Media.Color.FromArgb(128, 128, 128, 128));
                writeableBitmap.DrawRectangle(x1, y1, x2, y2, color);

            }
        }
Exemple #21
0
        void setFrame()
        {
            camera.GetPreviewBufferYCbCr(bufferLast);
            int[] pixelData = new int[(int)(camera.PreviewResolution.Width * camera.PreviewResolution.Height)];  //640x480

            camera.GetPreviewBufferArgb32(pixelData);
            zapisany = new WriteableBitmap((int)camera.PreviewResolution.Width, (int)camera.PreviewResolution.Height);

            pixelData.CopyTo(zapisany.Pixels, 0);

            zapisany.Invalidate();

            zapisany = zapisany.Resize(t, t,
                                                                 WriteableBitmapExtensions.Interpolation.Bilinear);

            /*            int ApetureMin = -(2 / 2);
            int ApetureMax = (2 / 2);
            for (int x = 0; x < t; ++x)
            {
                for (int y = 0; y < t; ++y)
                {
                    int RValue = 0;
                    int GValue = 0;
                    int BValue = 0;
                    for (int x2 = ApetureMin; x2 < ApetureMax; ++x2)
                    {
                        int TempX = x + x2;
                        if (TempX >= 0 && TempX < t)
                        {
                            for (int y2 = ApetureMin; y2 < ApetureMax; ++y2)
                            {
                                int TempY = y + y2;
                                if (TempY >= 0 && TempY < t)
                                {
                                    Color TempColor = zapisany.GetPixel(TempX, TempY);
                                    if (TempColor.R > RValue)
                                        RValue = TempColor.R;
                                    if (TempColor.G > GValue)
                                        GValue = TempColor.G;
                                    if (TempColor.B > BValue)
                                        BValue = TempColor.B;
                                }
                            }
                        }
                    }
                    //Color TempPixel = Color.FromArgb(0, (byte) RValue, (byte) GValue, (byte) BValue);
                    zapisany.SetPixel(x, y, (byte)RValue, (byte)GValue, (byte)BValue);
                }
            }*/

            /*        for (int i = 0; i < 128; i++)
                    {
                        for (int j = 0; j < 128; j++)
                        {
                            var a = zapisany.GetPixel(i, j);
                            byte d = (byte)((a.R + a.G + a.B) / 3);

                           zapisany.SetPixel(i, j, d, d, d);
                        }
                    }*/
            /*            for (int i = 0; i < t; i++)
            {
                for (int j = 0; j < t; j++)
                {
                    var a = zapisany.GetPixel(i, j);
                    byte d = (byte)((a.R + a.G + a.B) / 3);

                    zapisany.SetPixel(i, j, d, d, d);
                }
            }*/

            for (int i = 0; i < t; i++)
            {
                for (int j = 0; j < t; j++)
                {
                    var a = zapisany.GetPixel(i, j);
                    if ((a.R + a.G + a.B) / 3 < 128)
                    {
                        zapisany.SetPixel(i, j, 0, 0, 0);
                    }
                    else
                    {
                        zapisany.SetPixel(i, j, 255, 255, 255);
                    }
                }
            }
        }
Exemple #22
0
        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            lastCount = count;
            count = 0;
            int[] pixelData = new int[(int)(camera.PreviewResolution.Width * camera.PreviewResolution.Height)];  //640x480

            camera.GetPreviewBufferArgb32(pixelData);

            WriteableBitmap freezeWriteableBitmap = new WriteableBitmap((int)camera.PreviewResolution.Width, (int)camera.PreviewResolution.Height);

            pixelData.CopyTo(freezeWriteableBitmap.Pixels, 0);

            freezeWriteableBitmap.Invalidate();
             //   timer.Stop();
            int[] buffer1 = buffer;

            try
            {
                camera.GetPreviewBufferArgb32(buffer);
               // camera.GetPreviewBufferY(bufferr);
            }
            catch (Exception e)
            {

            }
            //int t = 128;
               freezeWriteableBitmap = freezeWriteableBitmap.Resize(t, t,
                                                                 WriteableBitmapExtensions.Interpolation.Bilinear);
            /*
            for (int i = 0; i < bufferr.Length; i++)
            {
                if (bufferLast[i] != bufferr[i])
                {
                    count++;
                }
            }*/
            /*
              for (int i = 0; i < t; i++)
               {
               for (int j = 0; j < t; j++)
               {
                   var a = freezeWriteableBitmap.GetPixel(i, j);
                  byte d = (byte)((a.R + a.G + a.B)/3);

                    freezeWriteableBitmap.SetPixel(i,j, d,d,d);
               }
               }*/
            int srednia = 0;
            for (int i = 0; i < t; i++)
            {
                for (int j = 0; j <t; j++)
                {
                    var d = freezeWriteableBitmap.GetPixel(i, j);

                    srednia += (d.R + d.G + d.B)/ 3;
                }
            }
            srednia = srednia/(128*128);
            for (int i = 0; i < t; i++)
            {
                for (int j = 0; j <t; j++)
                {
                    var a = freezeWriteableBitmap.GetPixel(i, j);
                    if ((a.R + a.G + a.B)/3 <srednia)
                    {
                        freezeWriteableBitmap.SetPixel(i,j,0,0,0);
                    }
                    else
                    {
                        freezeWriteableBitmap.SetPixel(i,j,255,255,255);
                    }
                }
            }

               /*          int ApetureMin = -(10 / 2);
               int ApetureMax = (2 / 2);
            for (int x = 0; x < t; ++x)
            {
                for (int y = 0; y < t; ++y)
                {
                    int RValue = 0;
                    int GValue = 0;
                    int BValue = 0;
                    for (int x2 = ApetureMin; x2 < ApetureMax; ++x2)
                    {
                        int TempX = x + x2;
                        if (TempX >= 0 && TempX < t)
                        {
                            for (int y2 = ApetureMin; y2 < ApetureMax; ++y2)
                            {
                                int TempY = y + y2;
                                if (TempY >= 0 && TempY < t)
                                {
                                    Color TempColor = freezeWriteableBitmap.GetPixel(TempX, TempY);
                                    if (TempColor.R > RValue)
                                        RValue = TempColor.R;
                                    if (TempColor.G > GValue)
                                        GValue = TempColor.G;
                                    if (TempColor.B > BValue)
                                        BValue = TempColor.B;
                                }
                            }
                        }
                    }
                    //Color TempPixel = Color.FromArgb(0, (byte) RValue, (byte) GValue, (byte) BValue);
                    freezeWriteableBitmap.SetPixel(x, y, (byte)RValue, (byte)GValue, (byte)BValue);
                }
            }*/

            kopia.Source = freezeWriteableBitmap;

            for (int i = 0; i < t; i++)
            {
                for (int j = 0; j < t; j++)
                {

                    if (zapisany.GetPixel(i, j) != freezeWriteableBitmap.GetPixel(i, j))
                    {
                        count++;

                    }
                }
            }
            if ((count - lastCount) > 100)
            {
                startButton.Content = "Ruch";
            }
            else
            {
                startButton.Content = "Brak ruchu";
            }

            if (count < 200)
            {
                setFrame();
            }
        }
Exemple #23
0
        public override bool MoveTool(TileMouseEventArgs e)
        {
            WriteableBitmap bmp;

            if (_startPoint != null) _endPoint = e.Tile;
            CheckDirectionandDraw(e);
            ToolAnchorMode mode = ToolAnchorMode.Center;

            // Line draw preview
            if (_isRightDown && _startPoint != null && _endPoint != null) {
                var sp = (PointInt32)_startPoint;
                var ep = (PointInt32)_endPoint;
                var delta = ep - sp;
                var rect = new RectI(new PointInt32(), new SizeInt32(Math.Abs(delta.X) + 1, Math.Abs(delta.Y) + 1));

                // figure out exactly which PreviewMode
                mode = 0;
                if      (delta.X <  0) mode += (int)ToolAnchorModeParts.Left;
                else if (delta.X == 0) mode += (int)ToolAnchorModeParts.Center;
                else if (delta.X >  0) mode += (int)ToolAnchorModeParts.Right;

                if      (delta.Y <  0) mode += (int)ToolAnchorModeParts.Top;
                else if (delta.Y == 0) mode += (int)ToolAnchorModeParts.Middle;
                else if (delta.Y >  0) mode += (int)ToolAnchorModeParts.Bottom;

                // which direction to draw the line
                var linePnts = new PointInt32[2];
                switch (mode) {
                    case ToolAnchorMode.TopLeft:     linePnts = new[] { rect.BottomRight, rect.TopLeft }; break;
                    case ToolAnchorMode.TopRight:    linePnts = new[] { rect.BottomLeft, rect.TopRight }; break;
                    case ToolAnchorMode.BottomLeft:  linePnts = new[] { rect.TopRight, rect.BottomLeft }; break;
                    case ToolAnchorMode.BottomRight: linePnts = new[] { rect.TopLeft, rect.BottomRight }; break;
                    default:  // has middle or center, order doesn't matter
                        linePnts = new[] { rect.TopLeft, rect.BottomRight };
                        break;
                }

                bmp = new WriteableBitmap(
                    rect.W,
                    rect.H,
                    96,
                    96,
                    System.Windows.Media.PixelFormats.Bgra32,
                    null);

                bmp.Clear();
                foreach (PointInt32 p in WorldRenderer.DrawLine(linePnts[0], linePnts[1])) {
                    if (_selection.IsValid(p)) bmp.SetPixel(p.X, p.Y, previewColor);
                }
            }
            // Single dot
            else {
                bmp = new WriteableBitmap(
                    1,
                    1,
                    96,
                    96,
                    System.Windows.Media.PixelFormats.Bgra32,
                    null);

                bmp.Clear();
                bmp.SetPixel(0, 0, previewColor);
            }

            _properties.Image = bmp;
            _properties.PreviewMode = mode;

            return false;
        }
Exemple #24
0
        internal BitmapSource ToBitmap(  byte[] pixels, int width, int height)
        {
            //X8R8G8B8
            int index = 0;
            WriteableBitmap bb = new WriteableBitmap(width, height);

            for (int y = 0; y < bb.PixelHeight; y++)
            {
                for (int x = 0; x < bb.PixelWidth; x++)
                {
                    bb.SetPixel(x, y, Color.FromArgb(255, pixels[index], pixels[index + 1], pixels[index + 2]));
                    index += 4;
                }
            }
               return  bb;
        }
Exemple #25
0
        public override WriteableBitmap PreviewTool()
        {
            var bmp = new WriteableBitmap(
                1,
                1,
                96,
                96,
                System.Windows.Media.PixelFormats.Bgra32,
                null);

            bmp.Clear();
            bmp.SetPixel(0, 0, previewColor);

            return bmp;
        }
        //Point? mp = null;
        //private void resizeHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    mp = e.GetPosition((UIElement)sender);
        //    ((UIElement)sender).CaptureMouse();
        //}
        //private void resizeHandle_MouseMove(object sender, MouseEventArgs e)
        //{
        //    if (mp != null)
        //    {
        //    }
        //}
        //private void resizeHandle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        //{
        //    mp = null;
        //    ((Canvas)sender).ReleaseMouseCapture();
        //}
        private void LayoutRoot_Drop(object sender, DragEventArgs e)
        {
            var file = ((FileInfo[])e.Data.GetData(DataFormats.FileDrop))[0];
            string fn = file.Name.ToLower();
            WriteableBitmap wb = null;
            if (fn.EndsWith(".jpg") || fn.EndsWith(".png"))
            {
                BitmapImage bi = new BitmapImage();
                try
                {
                    bi.SetSource(file.OpenRead());
                    if (bi.PixelWidth < 50 || bi.PixelHeight < 50)
                    {
                        MessageBox.Show("画像サイズが小さすぎます");
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("エラー");
                    return;
                }
                wb = new WriteableBitmap(bi);

            }
            else if (fn.EndsWith(".bmp"))
            {
                IImageDecoder dec = new BmpDecoder();
                FileStream fs = file.OpenRead();
                ImageTools.Image img = new ImageTools.Image();
                try
                {
                    dec.Decode(img, fs);
                }
                catch
                {
                    MessageBox.Show("エラー");
                    return;
                }
                if (img.Width < 50 || img.Height < 50)
                {
                    MessageBox.Show("画像サイズが小さすぎます");
                    return;
                }
                wb = new WriteableBitmap(img.Width, img.Height);
                byte[] data = img.GetPixels();
                for (int y = 0; y < img.Height; y++)
                {
                    for (int x = 0; x < img.Width; x++)
                    {
                        int idx = (x + y * img.Width) * 4;
                        wb.SetPixel(x, y, Color.FromArgb(data[idx + 3], data[idx], data[idx + 1], data[idx + 2]));
                    }
                }
                fs.Close();
            }
            else
            {
                MessageBox.Show("エラー");
                return;
            }
            try
            {
                SetImage(wb);
            }
            catch
            {
                MessageBox.Show("エラー");
            }
        }
        private void DrawGrid(WriteableBitmap writeableBitmap)
        {
            Color color = Colors.White;
            color.A = 50;
            
            if (OverlayActivated)
            {
                if (SelectedOverlay != null && File.Exists(SelectedOverlay))
                {
                    if (_overlayImage == null)
                    {
                        BitmapImage bitmapSource = new BitmapImage();
                        bitmapSource.DecodePixelWidth = writeableBitmap.PixelWidth;
                        bitmapSource.BeginInit();
                        bitmapSource.UriSource = new Uri(SelectedOverlay);
                        bitmapSource.EndInit();
                        _overlayImage = BitmapFactory.ConvertToPbgra32Format(bitmapSource);
                        _overlayImage.Freeze();
                    }
                    int x = writeableBitmap.PixelWidth * OverlayScale / 100;
                    int y = writeableBitmap.PixelHeight * OverlayScale / 100;
                    int xx = writeableBitmap.PixelWidth * OverlayHorizontal / 100;
                    int yy = writeableBitmap.PixelWidth * OverlayVertical / 100;
                    writeableBitmap.Blit(
                        new Rect(0 + (x / 2) + xx, 0 + (y / 2) + yy, writeableBitmap.PixelWidth - x,
                            writeableBitmap.PixelHeight - y),
                        _overlayImage,
                        new Rect(0, 0, _overlayImage.PixelWidth, _overlayImage.PixelHeight));
                }
            }

            switch (GridType)
            {
                case 1:
                {
                    for (int i = 1; i < 3; i++)
                    {
                        writeableBitmap.DrawLine(0, (int) ((writeableBitmap.Height/3)*i),
                            (int) writeableBitmap.Width,
                            (int) ((writeableBitmap.Height/3)*i), color);
                        writeableBitmap.DrawLine((int) ((writeableBitmap.Width/3)*i), 0,
                            (int) ((writeableBitmap.Width/3)*i),
                            (int) writeableBitmap.Height, color);
                    }
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 2:
                {
                    for (int i = 1; i < 10; i++)
                    {
                        writeableBitmap.DrawLine(0, (int) ((writeableBitmap.Height/10)*i),
                            (int) writeableBitmap.Width,
                            (int) ((writeableBitmap.Height/10)*i), color);
                        writeableBitmap.DrawLine((int) ((writeableBitmap.Width/10)*i), 0,
                            (int) ((writeableBitmap.Width/10)*i),
                            (int) writeableBitmap.Height, color);
                    }
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 3:
                {
                    writeableBitmap.DrawLineDDA(0, 0, (int) writeableBitmap.Width,
                        (int) writeableBitmap.Height, color);

                    writeableBitmap.DrawLineDDA(0, (int) writeableBitmap.Height,
                        (int) writeableBitmap.Width, 0, color);
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                case 4:
                {
                    writeableBitmap.DrawLineDDA(0, (int) (writeableBitmap.Height/2), (int) writeableBitmap.Width,
                        (int) (writeableBitmap.Height/2), color);

                    writeableBitmap.DrawLineDDA((int) (writeableBitmap.Width/2), 0,
                        (int) (writeableBitmap.Width/2), (int) writeableBitmap.Height, color);
                    writeableBitmap.SetPixel((int) (writeableBitmap.Width/2), (int) (writeableBitmap.Height/2), 128,
                        Colors.Red);
                }
                    break;
                default:
                    break;
            }

            if (ShowRuler)
            {
                int x1 = writeableBitmap.PixelWidth*HorizontalMin/100;
                int x2 = writeableBitmap.PixelWidth*HorizontalMax/100;
                int y2 = writeableBitmap.PixelHeight*(100-VerticalMin)/100;
                int y1 = writeableBitmap.PixelHeight*(100-VerticalMax)/100;

                FillRectangle2(writeableBitmap, 0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, Color.FromArgb(128, 128, 128, 128));
                FillRectangleDeBlend(writeableBitmap, x1, y1, x2, y2, Color.FromArgb(128, 128, 128, 128));
                writeableBitmap.DrawRectangle( x1, y1, x2, y2, color);

            }

        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight;
            if ((int)screenHeight == 0)
                throw new Exception("screenHeight");
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;
            Image mainImage = new Image();
            mainPage.Width = screenWidth;
            mainPage.Height = screenHeight;
            mainImage.Width = screenWidth;
            mainImage.Height = screenHeight;
            mainPage.Content = mainImage;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mainImage.Source = mFrontBuffer;
            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));
                return oldColor & 0xffffff;
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                mCurrentDrawTarget.DrawLine(x1, y1, x2, y2, (int)mCurrentColor);
            };

            TextBlock textBlock = new TextBlock();
            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0) return;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b = new WriteableBitmap(textBlock, null);
                    mCurrentDrawTarget.Blit(new Rect(left, top, b.PixelWidth, b.PixelHeight),
                        b,
                        new Rect(0, 0, b.PixelWidth, b.PixelHeight));
                });
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth = (int)textBlock.ActualWidth;
                    textHeight = (int)textBlock.ActualHeight;
                });

                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0) return;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b = new WriteableBitmap(textBlock, null);
                    Rect dstRect = new Rect(left, top, b.PixelWidth, b.PixelHeight);
                    Rect srcRect = new Rect(0, 0, b.PixelWidth, b.PixelHeight);
                    // cliprect..
                    Rect clipRect = new Rect(0, 0, mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
                    clipRect.Intersect(dstRect);
                    if (clipRect.IsEmpty == true)
                    {
                        return;
                    }

                    mCurrentDrawTarget.Blit(dstRect,
                        b,
                        srcRect);
                });
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth = (int)textBlock.ActualWidth;
                    textHeight = (int)textBlock.ActualHeight;
                });

                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + 0);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + 4);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {

                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex) return oldDrawTarget;
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return oldDrawTarget;
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return oldDrawTarget;
            };

            syscalls.maGetScrSize = delegate()
            {
                return MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                int w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return MoSync.Util.CreateExtent(w, h);
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Rect srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(srcRectPtr + 0);
                int srcRectY = dataMemory.ReadInt32(srcRectPtr + 4);
                int srcRectW = dataMemory.ReadInt32(srcRectPtr + 8);
                int srcRectH = dataMemory.ReadInt32(srcRectPtr + 12);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + 0);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + 4);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);
                // mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);

                DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                if (bitmap == null) return MoSync.Constants.RES_OUT_OF_MEMORY;
                res.SetInternalObject(bitmap);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        bitmap = new WriteableBitmap(width, height);
                    });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels = bitmap.Pixels;
                    int numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                runtime.SetResource(_placeholder,
                    new Resource(
                        bitmap,
                        MoSync.Constants.RT_IMAGE
                        )
                    );
                return MoSync.Constants.RES_OK;
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int dstX = dataMemory.ReadInt32(_dstPoint + 0);
                int dstY = dataMemory.ReadInt32(_dstPoint + 4);
                int srcRectX = dataMemory.ReadInt32(_srcRect + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                int[] pixels = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4; // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(_srcRect + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                int lineDst = _dst;
                byte[] data = src.ToByteArray(srcRectY * src.PixelWidth,
                    srcRectH * src.PixelWidth);
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                        lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory mem = (Memory)res.GetInternalObject();

                Stream s = mem.GetStream(_offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();
                runtime.SetResource(
                    _placeholder,
                    new Resource(
                        bitmap,
                        MoSync.Constants.RT_IMAGE
                        )
                );

                return MoSync.Constants.RES_OK;
            };
        }
        /// <summary>
        /// A simple version of Canny Edge detection
        /// </summary>
        public static WriteableBitmap edgeDetection(WriteableBitmap bmp)
        {
            WriteableBitmap temp = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);
            bmp = ToGrayScale(bmp);
            bmp = WriteableBitmapExtensions.Convolute(bmp, WriteableBitmapExtensions.KernelGaussianBlur3x3);
            double delta = 1.0;
            // thetaThr = theta threshold value
            // magThr = magnitude threshold value
            int theta = 200, thetaThr = 360, magThr = 20;
            for (int r = 0; r < bmp.PixelHeight; r++)
            {
                for (int c = 0; c < bmp.PixelWidth; c++)
                {
                    double pdx = pixDiffdx(bmp, c, r);
                    double pdy = pixDiffdy(bmp, c, r);
                    double th = gradTheta(bmp, c, r, pdx, pdy);
                    double gm = gradMagnitude(pdx, pdy);

                    // Can also use this
                    // if(Math.Abs(th) <= thetaThr && gm >= magThr)
                    // if more intensity of brightness is needed

                    if (gm >= 20 && (th < 90 && th > -90))
                    {
                        // is an edge
                        temp.SetPixel(c, r, Colors.White);
                    }
                    else
                    {
                        // not an edge
                        temp.SetPixel(c, r, Colors.Black);
                    }
                }
            }
            return temp;
        }