Android 圖片的合成


本文實現在Android下圖片的合成

布局設計比較簡單:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

邏輯部分代碼如下:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView iv = (ImageView) findViewById(R.id.iv);

        // 圖片合成-畫布 先去畫A 再去畫B
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.test); // bitmap為只讀的

        Bitmap alterBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), bitmap.getConfig());
        Canvas canvas = new Canvas(alterBitmap);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);

        canvas.drawBitmap(bitmap, new Matrix(), paint);

        Bitmap ic_luncher = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);
        
        canvas.drawBitmap(ic_luncher, new Matrix(), paint);
        iv.setImageBitmap(alterBitmap);

    }

}

最后的效果如下:

打開android手機的API Demo圖標

選擇Graphics,接着選擇Xfermodes,如下:

這里顯示了各種圖片合成后的模式,我們可以在代碼中實現,這里采用DARKEN模式,代碼如下:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView iv = (ImageView) findViewById(R.id.iv);

        // 圖片合成-畫布 先去畫A 再去畫B
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.test); // bitmap為只讀的

        Bitmap alterBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), bitmap.getConfig());
        Canvas canvas = new Canvas(alterBitmap);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));

        canvas.drawBitmap(bitmap, new Matrix(), paint);

        Bitmap ic_luncher = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        canvas.drawBitmap(ic_luncher, new Matrix(), paint);
        iv.setImageBitmap(alterBitmap);

    }

}

效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM