/* Моя кошка замечательно разбирается в программировании. Стоит мне объяснить проблему ей - и все становится ясно. */
John Robbins, Debugging Applications, Microsoft Press, 2000
Метод setShadowLayer() позволяет наложить эффект размытой тени на изображение. Применять желательно к изображениям с прозрачным фоном, иначе можете не увидеть эффекта.
Пример написан на основе статьи Example to draw Bitmap with ShadowLayer и упрощён для наглядности.Создадим разметку.
<LinearLayout 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:orientation="vertical"
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" >
<Button
android:id="@+id/loadimage1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />
<TextView
android:id="@+id/sourceuri1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/processing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Processing" />
<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
</LinearLayout>
Загружаем картинку из галереи и применяем к ней эффект. Для примера используйте небольшие картинки, так как код не оптимизирован для работы с большими изображениями и можно получить ошибку нехватки памяти.
package ru.alexanderklimov.test;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnLoadImage1;
TextView textSource1;
Button btnProcessing;
ImageView imageResult;
final int RQS_IMAGE1 = 1;
Uri source1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage1 = (Button) findViewById(R.id.loadimage1);
textSource1 = (TextView) findViewById(R.id.sourceuri1);
btnProcessing = (Button) findViewById(R.id.processing);
imageResult = (ImageView) findViewById(R.id.result);
btnLoadImage1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});
btnProcessing.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (source1 != null) {
Bitmap processedBitmap = setShadow();
if (processedBitmap != null) {
imageResult.setImageBitmap(processedBitmap);
Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Something wrong in processing!",
Toast.LENGTH_LONG).show();
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source1 = data.getData();
textSource1.setText(source1.toString());
break;
}
}
}
private Bitmap setShadow() {
Bitmap bm1 = null;
Bitmap bm2 = null;
Bitmap newBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(source1));
bm2 = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(source1));
int w;
w = bm1.getWidth();
int h;
h = bm1.getHeight();
Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
Paint paint = new Paint();
paint.setShadowLayer(50.0f, 5.0f, 5.0f, 0xFF0ff000);
newCanvas.drawBitmap(bm2, 0, 0, paint);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newBitmap;
}
}
Переделаем метод setShadow(), чтобы к картинке добавить тень, а также рамку вокруг картинки.
private Bitmap setShadow() {
Bitmap bm1 = null;
Bitmap newBitmap = null;
Bitmap newShadowBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(source1));
int w = bm1.getWidth();
int h = bm1.getHeight();
Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawColor(Color.BLACK);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
Rect frame = new Rect((int) (w * 0.05), (int) (w * 0.05),
(int) (w * 0.95), (int) (h * 0.95));
RectF frameF = new RectF(frame);
newCanvas.drawRect(frameF, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.DARKEN));
newCanvas.drawBitmap(bm1, 0, 0, paint);
/*
* Create shadow like outer frame
*/
// create BLACK bitmap with same size of the image
Bitmap bitmapFullGray = Bitmap.createBitmap(w, h, config);
Canvas canvasFullGray = new Canvas(bitmapFullGray);
canvasFullGray.drawColor(0xFF808080);
// create bigger bitmap with shadow frame
int shadowThick = 100;
int shadowRadius = 50;
newShadowBitmap = Bitmap.createBitmap(w + shadowThick
+ shadowRadius, h + shadowThick + shadowRadius, config);
Canvas newShadowCanvas = new Canvas(newShadowBitmap);
newShadowCanvas.drawColor(Color.WHITE);
// generate shadow
Paint paintShadow = new Paint();
paintShadow.setShadowLayer(shadowRadius, shadowThick, shadowThick,
0xFF000000);
newShadowCanvas.drawBitmap(bitmapFullGray, 0, 0, paintShadow);
// Place the image
paintShadow.clearShadowLayer();
newShadowCanvas.drawBitmap(newBitmap, 0, 0, paintShadow);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newShadowBitmap;
}