Bitmap で Pixel 操作してみた

Bitmap をピクセル単位で操作するには

getPixel(int x, int y)
または
getPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height)
を使ってPixelを取得、

setPixel(int x, int y, int color)
または
setPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height)
で設定します

というわけで、Pixel操作をしてみた

サンプルプログラム
  1. import android.app.Activity;  
  2. import android.content.Context;  
  3. import android.graphics.Bitmap;  
  4. import android.graphics.BitmapFactory;  
  5. import android.graphics.Canvas;  
  6. import android.graphics.Color;  
  7. import android.graphics.Paint;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10.   
  11. public class BitmapTest2 extends Activity {  
  12.   Bitmap bitmap;  
  13.   int pixels[];  
  14.   @Override  
  15.   public void onCreate(Bundle savedInstanceState) {  
  16.     super.onCreate(savedInstanceState);  
  17.     setContentView(new BitmapTest2View(this));  
  18.   }  
  19.   
  20.   class BitmapTest2View extends View {  
  21.     public BitmapTest2View(Context context) {  
  22.       super(context);  
  23.      
  24.       // リソースから Bitmap を取得   
  25.       bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);  
  26.      
  27.       // もし編集不可なら、編集可能な Bitmap を複製  
  28.       if (!bitmap.isMutable()) {  
  29.         bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);  
  30.       }  
  31.      
  32.       int width = bitmap.getWidth();  
  33.       int height = bitmap.getHeight();  
  34.       pixels = new int[width * height];  
  35.      
  36.       // Bitmap から Pixel を取得  
  37.       bitmap.getPixels(pixels, 0, width, 00, width, height);  
  38.      
  39.       // Pixel 操作部分  
  40.       for (int y = 0; y < height; y++) {  
  41.         for (int x = 0; x < width; x++) {  
  42.           int pixel = pixels[x + y * width];  
  43.        
  44.           pixels[x + y * width] = Color.argb(  
  45.               Color.alpha(pixel),   
  46.               Color.green(pixel),   
  47.               Color.blue(pixel),  
  48.               Color.red(pixel)  
  49.           );  
  50.         }  
  51.       }  
  52.      
  53.       // Bitmap に Pixel を設定  
  54.       bitmap.setPixels(pixels, 0, width, 00, width, height);  
  55.     }  
  56.     
  57.     @Override  
  58.     public void onDraw(Canvas canvas) {  
  59.       // Bitmap の描画  
  60.       canvas.drawBitmap(bitmap, 00new Paint());  
  61.     }  
  62.   }  
  63. }  

プログラムを実行すると...


こんな感じ!

なんか紫色だと違和感が...

参考サイト
http://developer.android.com/intl/ja/reference/android/graphics/Bitmap.html

0 件のコメント:

コメントを投稿